why My GridView was not displaying?
ascx CODE:
<asp:PlaceHolder ID="plcGridTest" runat="server">
<asp:GridView ID="grdTest" runat="server" AutoGenerateColumns="false"/>
</asp:PlaceHolder>
ascx.cs CODE:
protected void btnPesquisar_Click(object sender, EventArgs e)
{
string placa = string.Empty;
insereParameterPlaca(txtPlaca.Text.ToUpper(), out placa);
string transportadora = string.Empty;
transportadora = insereTransportadoraSelecionada();
string tiposWorkflow = string.Empty;
insereTiposWorkflow(chkBox_TiposOcorrencia.Items, out tiposWorkflow);
string cliente = string.Empty;
insereCliente(out cliente);
string query = string.Empty;
query = string.Format(SQL_GET_OCORRENCIAS_PARAMETRIZADO, placa, transportadora, tiposWorkflow, cliente);
using (var sqlDataAccess = new MSQLDataAccess(Util.GetIntegraConnectionString))
{
var datatable = sqlDataAccess.GetDataTable(query);
grdTest.Visible = true;
grdTest.DataSource = datatable;
grdTest.DataBind();
}
}
AutoGenarateColuns was marked as false and I'm runnig DataBind() command.
You should set AutoGenerateColumns="True", if you don't want to specify each column.
Related
I have a form with a table, a cancel button and a save button. The last column in the table is editable. The save button saves the edits to the last column. The problem I am having is when I save, the table posts back as having 0 rows in the SaveButton_ServerClick method.
HTML:
<%# Page validateRequest="false" Language="C#" AutoEventWireup="true" CodeBehind="xxxxxx.aspx.cs" Inherits="xxxxx.xxx" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="Form1" runat="server">
<asp:Table id="SettingsTable" runat="server" EnableViewState="true"></asp:Table>
<asp:Button id="CancelButton" runat="server" Text="Cancel"></asp:Button>
<asp:Button id="SaveButton" runat="server" Text="Save"></asp:Button>
</form>
</body>
</html>
C#:
const string CONFIG_SET_ID = "ConfigurationSetId";
const string CONFIG_SET_NAME = "ConfigurationSetName";
const string CONFIG_SET_DESC = "ConfigurationSetDescription";
const string APP_NAME = "AppName";
const string APP_ID = "AppId";
const string SET_CAT = "SettingCategory";
const string SET_DESC = "SettingDescription";
const string SET_CAT_ID = "SettingCategoryId";
const string TITLE = "title";
const int CONFIG_SET_CELL = 0;
const int APP_NAME_CELL = 1;
const int SET_CAT_CELL = 2;
const int SETTINGKEY_CELL = 3;
const int SETTINGVALUE_CELL = 4;
static Dictionary<string, ConfigurationDictionary> _cfgDics = new Dictionary<string, ConfigurationDictionary>();
protected void Page_Load(object sender, EventArgs e)
{
AppCfg.AppName = "xxxxx";
AppCfg.Initialize();
if (!Page.IsPostBack)
LoadSettings();
SaveButton.Click += SaveButton_ServerClick;
CancelButton.Click += CancelButton_ServerClick;
}
/// ADDING THIS FIXED THE POSTBACK PROBLEM.
void CancelButton_ServerClick(object sender, EventArgs e)
{
LoadSettings();
}
void SaveButton_ServerClick(object sender, EventArgs e)
{
foreach (TableRow row in SettingsTable.Rows)
{
if (row.Cells[SETTINGVALUE_CELL].Controls[0].GetType().Equals(typeof(TextBox)))
{
string appId = row.Cells[APP_NAME_CELL].Attributes[APP_ID];
string settingKey = row.Cells[SETTINGKEY_CELL].Text;
string settingValue = ((TextBox)row.Cells[SETTINGVALUE_CELL].Controls[0]).Text;
if (_cfgDics.ContainsKey(appId) && _cfgDics[appId][settingKey].Value != settingValue)
_cfgDics[appId][settingKey] = settingValue;
}
}
System.Threading.Thread.Sleep(1000);
LoadSettings();
}
void CancelButton_ServerClick(object sender, EventArgs e)
{
LoadSettings();
}
private void LoadSettings()
{
//foreach (ConfigurationDictionary dic in _cfgDics.Values)
// dic.Dispose();
//_cfgDics.Clear();
SettingsTable.Rows.Clear();
// Build Settings table
// Build Header row
TableRow headerRow = new TableRow();
headerRow.Cells.Add(new TableCell() { Text = "Config Set" });
headerRow.Cells.Add(new TableCell() { Text = "Application" });
headerRow.Cells.Add(new TableCell() { Text = "Category" });
headerRow.Cells.Add(new TableCell() { Text = "Setting Key" });
headerRow.Cells.Add(new TableCell() { Text = "Setting Value" });
SettingsTable.Rows.Add(headerRow);
IniFileEditor xxxIni = new IniFileEditor();
string dbConnString = xxxIni.ReadValue(ConfigurationDictionary.SECKEY, ConfigurationDictionary.SETTING_DB_KEY);
if (!string.IsNullOrEmpty(dbConnString))
{
// Build each setting
using (DatabaseAccess dba = new DatabaseAccess(dbConnString))
using (SqlCommand cmd = new SqlCommand("Select * from AllSettings"))
using (SqlDataReader reader = dba.GetSqlReader(cmd))
{
while (reader.Read())
{
TableRow row = new TableRow();
string appId = string.Empty;
row.Cells.Add(new TableCell() { Text = reader[CONFIG_SET_NAME].ToString() });
row.Cells[CONFIG_SET_CELL].Attributes[CONFIG_SET_ID] = reader[CONFIG_SET_ID].ToString();
row.Cells[CONFIG_SET_CELL].Attributes[TITLE] = reader[CONFIG_SET_DESC].ToString();
row.Cells.Add(new TableCell() { Text = reader[APP_NAME].ToString() });
appId = reader[APP_ID].ToString();
row.Cells[APP_NAME_CELL].Attributes[APP_ID] = appId;
row.Cells[APP_NAME_CELL].Attributes[TITLE] = string.Format("AppId:\t{0} \r\nMachine:\t{1} \r\nIPAddress:\t{2}",
reader[APP_ID],
reader["MachineName"],
reader["MachineAddress"]);
row.Cells.Add(new TableCell() { Text = reader[SET_CAT].ToString() });
row.Cells[SET_CAT_CELL].Attributes[SET_CAT_ID] = reader[SET_CAT_ID].ToString();
row.Cells.Add(new TableCell() { Text = reader["SettingKey"].ToString() });
row.Cells[SETTINGKEY_CELL].Attributes[TITLE] = reader[SET_DESC].ToString();
TextBox valueTextbox = new TextBox();
valueTextbox.Text = reader["SettingValue"].ToString();
row.Cells.Add(new TableCell());
row.Cells[SETTINGVALUE_CELL].Controls.Add(valueTextbox);
if (!_cfgDics.ContainsKey(appId))
_cfgDics.Add(appId, new ConfigurationDictionary(appId));
SettingsTable.Rows.Add(row);
}
}
}
}
Try creating the dynamic controls every time in the PreInit event, that is the only way ViewState will ever get applied on Post-Back.
protected void Page_PreInit(object sender, EventArgs e)
{
LoadSettings();
}
Upon post back the table data been lost. so please keep the table data in the sessionstate or viewstate.
I am working with dynamically created text fields. Most solutions I have found thus far have been related to retaining view state on postback, but I believe I have taken care of that issue. On postback, the values that are in the text fields are retained.
The issue I am having: I can't get the database values currently stored to load in the dynamic fields. I am currently calling loadUpdates() to try to do this, but unsure how to grab the data row, while also making sure I can continue to add new fields (or remove them). How can I achieve this?
"txtProjectsUpdate" is the text field, "hidFKID" is the foreign key to a parent table, and "hidUpdateID" is the hidden value of the primary key in the child table (the values I am attempting to load).
Markup:
<div>
<asp:Button ID="btnAddTextBox" runat="server" Text="Add" OnClick="btnAddTextBox_Click" />
<asp:Placeholder ID="placeHolderControls" runat="server"/>
</div>
<asp:TextBox runat = "server" ID = "hidUpdateID" />
<asp:HiddenField runat = "server" ID = "hidFKID" />
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
for (var i = 0; i < TextBoxCount; i++)
AddTextBox(i);
}
if (!IsPostBack)
{
DataTable dt = new DataTable();
dt = selectDetails();
tryHidFKID(hidFKID, dt.Rows[0]["fkprjNumber"].ToString());
loadUpdates();
}
}
protected void btnAddTextBox_Click(object sender, EventArgs e)
{
AddTextBox(TextBoxCount);
TextBoxCount++;
}
private int TextBoxCount
{
get
{
var count = ViewState["txtBoxCount"];
return (count == null) ? 0 : (int)count;
}
set { ViewState["txtBoxCount"] = value; }
}
private void btnRemove_Click(object sender, EventArgs e)
{
var btnRemove = sender as Button;
if (btnRemove == null) return;
btnRemove.Parent.Visible = false;
}
private void AddTextBox(int index)
{
var panel = new Panel();
panel.Controls.Add(new TextBox
{
ID = string.Concat("txtProjectUpdates", index),
Rows = 5,
Columns = 130,
TextMode = TextBoxMode.MultiLine,
CssClass = "form-control",
MaxLength = 500
});
panel.Controls.Add(new TextBox
{
ID = string.Concat("hidUpdateID", index)
});
var btn = new Button { Text = "Remove" };
btn.Click += btnRemove_Click;
panel.Controls.Add(btn);
placeHolderControls.Controls.Add(panel);
}
protected void loadUpdates()
{
DataTable dt = dbClass.ExecuteDataTable
(
"spSelectRecords", <db>, new SqlParameter[1]
{
new SqlParameter ("#vFKPrjNumber", hidFKID.Value)
}
);
AddTextBox(TextBoxCount);
TextBoxCount++;
}
protected void tryHidFKID(HiddenField hidFKID, string txtSelected)
{
try
{
hidFKID.Value = txtSelected;
}
catch
{
hidFKID.Value = "";
}
}
I am using a linkbutton within a gridview control.I want to open the link into a new tab. Link button:
<asp:LinkButton ID="lbtnEditCompany" CssClass="ahrefSearch" Text="Select" runat="server" OnClick="lbtnEditCompany_Click" />
Source Code :
protected void lbtnEditCompany_Click(object sender, EventArgs e)
{
try
{
LinkButton button = (LinkButton)sender;
SiteID = button.CommandArgument;
DataSet set = DataAccess.GetAllCorporateSites(SearchbyAlphabet, SessionManager.SaleID, SearchbyAssociate);
string str = "";
for (int i = 0; (i < set.Tables[0].Rows.Count) && (str == ""); i++)
{
if (SiteID == set.Tables[0].Rows[i]["ID"].ToString())
{
str = set.Tables[0].Rows[i]["CompanyName"].ToString();
}
}
SessionManager.WidgetId = Convert.ToInt32(SiteID);
SessionManager.SalesPersonSiteName = str;
base.Response.Redirect("~/Corporate/WidgetDetails.aspx", false);
}
catch (Exception exception)
{
HandlePageError(exception);
}
}
Try below code
Response.Write(String.Format("window.open('{0}','_blank')", ResolveUrl("~/Corporate/WidgetDetails.aspx")));
I'm using PostBackUrl to post my control from a "firstwebpage.aspx" to a "secondwebpage.aspx" so that I would be able to generate some configuration files.
I do understand that I can make use of PreviousPage.FindControl("myControlId") method in my secondwebpage.aspx to get my control from "firstwebpage.aspx"and hence grab my data and it worked.
However, it seems that this method does not work on controls which I generated programmically during runtime while populating them in a table in my firstwebpage.aspx.
I also tried using this function Response.Write("--" + Request["TextBox1"].ToString() + "--");
And although this statement do printout the text in the textfield on TextBox1, it only return me the string value of textbox1. I am unable to cast it to a textbox control in the following format too
TextBox temptextBox = (TextBox)Request["TextBox1"];
My question is, how can I actually access the control which i generated programmically in "firstwebpage.aspx" on "secondwebpage.aspx"?
Please advice!
thanks alot!
//my panel and button in aspx
<asp:Panel ID="Panel2" runat="server"></asp:Panel>
<asp:Button ID="Button1" runat="server" Text="Generate Xml" PostBackUrl="~/WebForm2.aspx" onclick="Button1_Click" />
//this is my function to insert a line into the panel
public void createfilerow(string b, string path, bool x86check, bool x86enable, bool x64check, bool x64enable)
{
Label blank4 = new Label();
blank4.ID = "blank4";
blank4.Text = "";
Panel2.Controls.Add(blank4);
CheckBox c = new CheckBox();
c.Text = b.Replace(path, "");
c.Checked = true;
c.ID = "1a";
Panel2.Controls.Add(c);
CheckBox d = new CheckBox();
d.Checked = x86check;
d.Enabled = x86enable;
d.ID = "1b";
Panel2.Controls.Add(d);
CheckBox e = new CheckBox();
e.Checked = x64check;
e.Enabled = x64enable;
e.ID = "1c";
Panel2.Controls.Add(e);
}
//my virtual path in WebForm2.aspx
<%# PreviousPageType VirtualPath="~/WebForm1.aspx" %>
//my pageload handler
protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null)
{
CheckBox tempCheckbox = (CheckBox)Page.PreviousPage.FindControl("1a");
Button1.Text = tempCheckbox.Text;
}
}
//handler which will populate the panel upon clicking
protected void Button7_Click(object sender, EventArgs e)
{
//get foldername
if (!Directory.Exists(#"myfilepath" + TextBox2.Text))
{
//folder does not exist
//do required actions
return;
}
string[] x86files = null;
string[] x64files = null;
string[] x86filespath = null;
string[] x64filespath = null;
ArrayList common = new ArrayList();
if (Directory.Exists(#"myfilepath" + TextBox2.Text + "\\x86"))
x86files = Directory.GetFileSystemEntries("myfilepath" + TextBox2.Text + "\\x86");
if (Directory.Exists(#"myfilepath" + TextBox2.Text + "\\x64"))
x64files = Directory.GetFileSystemEntries("myfilepath" + TextBox2.Text + "\\x64");
//some codes to convert x64files and x86files to string[]
//The header for Panel, 4 column
Label FL = new Label();
FL.ID = "flavourid";
FL.Text = "Flavour";
Panel2.Controls.Add(FL);
Label filetext = new Label();
filetext.ID = "filenamelabel";
filetext.Text = "File(s)";
Panel2.Controls.Add(filetext);
Label label86 = new Label();
label86.ID = "label86";
label86.Text = "x86";
Panel2.Controls.Add(label86);
Label label64 = new Label();
label64.ID = "label64";
label64.Text = "x64";
Panel2.Controls.Add(label64);
//a for loop determine number of times codes have to be run
for (int a = 0; a < num; a++)
{
ArrayList location = new ArrayList();
if (//this iteration had to be run)
{
string path = null;
switch (//id of this iteration)
{
case id:
path = some network address
}
//check the current version of iternation
string version = //version type;
//get the platform of the version
string platform = //platform
if (curent version = certain type)
{
//do what is required.
//build a list
}
else
{
//normal routine
//do what is required
//build a list
}
//populating the panel with data from list
createflavourheader(a);
//create dynamic checkboxes according to the list
foreach(string s in list)
//createrow parameter is by version type and platform
createfilerow(readin, path, true, true, false, false);
}
}
}
form1.Controls.Add(Panel2);
}
Sorry can't show you the full code as it is long and I believe it should be confidential even though i wrote them all
Yes you can access, Below is an example
// On Page1.aspx I have a button for postback
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
PostBackUrl="~/Page2.aspx" />
// Page1.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
TextBox t = new TextBox(); // created a TextBox
t.ID = "myTextBox"; // assigned an ID
form1.Controls.Add(t); // Add to form
}
Now on the second page I will get the value of TextBox as
// Page2.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null)
{
TextBox t = (TextBox) PreviousPage.FindControl("myTextBox");
string mytboxvalue = t.Text;
}
// OR
string myTextBoxValue = Request.Form["myTextBox"];
}
Updated Answer:
Panel myPanel = new Panel();
myPanel.ID = "myPanel";
TextBox t = new TextBox();
t.ID = "myTextBox";
myPanel.Controls.Add(t);
TextBox t1 = new TextBox();
t1.ID = "myTextBox1";
myPanel.Controls.Add(t1);
// Add all your child controls to your panel and at the end add your panel to your form
form1.Controls.Add(myPanel);
// on the processing page you can get the values as
protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null)
{
TextBox t = (TextBox) PreviousPage.FindControl("myTextBox");
string mytboxvalue = t.Text;
}
string myTextBoxValue = Request.Form["myTextBox1"];
}
I also tried using this function Response.Write("--" +
Request["TextBox1"].ToString() + "--"); And although this statement do
printout the text in the textfield on TextBox1, it only return me the
string value of textbox1. I am unable to cast it to a textbox control
in the following format too
TextBox temptextBox = (TextBox)Request["TextBox1"];
Hi lw,
I think you may try passing the type of control (e.g. 'tb') together with the content and creating a new object (e.g. TextBox) and assign it to templtexBox object.
My 20 cents.
Andy
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...