How to fix checkmarx stored XSS issue from datatable gridData binding - asp.net

Below is the code for retrieving datatable from database
protected DataTable ExecuteDataTableSQL(string strSQL)
{
using (OracleConnection connection = new OracleConnection(_strConnectionString))
{
dbAdapter.SelectCommand.Connection = connection;
connection.Open();
DataTable dtResult = new DataTable();
try
{
OracleCommand comm = dbAdapter.SelectCommand;
comm.CommandText = strSQL;
comm.CommandType = CommandType.Text;
dbAdapter.Fill(dtResult);
}
catch (Exception ex)
{
throw (ex);
}
return dtResult;
}
}
Below is the simplified code I am using the above method
DataTable dtResult = new DataTable();
string strSQL="some select statement";
dtResult = ExecuteDataTableSQL(strSQL);
if (dtResult.Rows.Count > 0)
{
DataGrid dg = new DataGrid();
dg.DataSource = dtResult;
dg.DataBind();
}
Checkmarx reports this as stored XSS as gets data from the database, for the dtResult element. This element’s value then flows through the code without being properly filtered or encoded and is eventually displayed to the user in method
source: dbAdapter.Fill(dtResult);
destination: dg.DataSource = dtResult;
How to resolve the issue.

Related

Not able to retrieve image in gridview in asp.net

//This is the code of presentation layer
BusinessAccessLayer.BLogic obj1 = new BusinessAccessLayer.BLogic();
string i = DDMenu.SelectedValue;
DataTable dt = new DataTable();
dt=obj1.getBind(i);
GridView1.DataSource = dt;
GridView1.DataBind();
//This is the code of business access layer
DataAccessLayer.DBLogic obj1 = new DataAccessLayer.DBLogic();
public DataTable getBind(string i)
{
return obj1.getInstrument(i);
}
//This is the code of database access layer
public DataTable getInstrument(string i)
{
SqlConnection con = new SqlConnection(constr);
con.Open();
try
{
SqlCommand cmd = new SqlCommand("selectedval", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#category_id", i);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
catch
{
throw;
}
finally
{
con.Close();
}
}
Here I have inserted some images in sql server by insert query. But while binding the data to gridview I am not able to see those images in gridview.

data source does not support server-side data paging

i am currently trying to do paging for my gridview but once i allow paging in my gridview it will give me this error : The data source does not support server-side data paging.
this is my code for gridview :
SqlDataReader reader = cmd.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataSourceID = null;
GridView1.Visible = true;
GridView1.AllowPaging= true;
GridView1.DataBind();
conn.Close();
SqlDataReader is forward-only. Server-side Paging needs to be able to traverse the datasource both backward and forward. Use a different datasource, like SqlDataAdapter, which supports bi-directional traversal.
Example (as requested):
string query = string.Empty;
SqlConnection conn = null;
SqlCommand cmd = null;
SqlDataAdapter da = null;
DataSet ds = null;
try {
query = "SELECT * FROM table WHERE field = #value";
conn = new SqlConnection("your connection string");
cmd = new SqlCommand(query, conn);
cmd.Parameters.Add("value", SqlDbType.VarChar, 50).Value = "some value";
da = new SqlDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds);
if (ds.Tables.Count > 0) {
GridView1.DataSource = ds.Tables(0);
GridView1.AllowPaging = true;
GridView1.DataBind();
}
} catch (SqlException ex) {
//handle exception
} catch (Exception ex) {
//handle exception
} finally {
if (da != null) {
da.Dispose();
}
if (cmd != null) {
cmd.Dispose();
}
if (conn != null) {
conn.Dispose();
}
}
SqlDataAdapter is also from the System.Data.SqlClient Namespace.
Have you tried using a SqlDataAdapter to fill a DataSet/DataTable with your SQL results? Then use that DataTable as your data source for the GridView. Basic framework for filling your DataTable:
public DataTable GetDataTable(String connectionString, String query)
{
DataTable dataTable = new DataTable();
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(query, connection))
{
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(command))
{
dataAdapter.Fill(dataTable);
}
}
}
}
catch
{
}
return dataTable;
}
And then you can use that DataTable as your GridView DataSource:
String connectionString = "Data Source=<datasource>;Initial Catalog=<catalog>;User Id=<userID>;Password=<password>;";
String query = "SELECT * FROM TABLE_NAME WHERE ID=BLAH";
GridView1.DataSource = GetDataTable(connectionString, query);
GridView1.DataSourceID = null;
GridView1.Visible = true;
GridView1.AllowPaging= true;
GridView1.DataBind();
Hopefully this will help.
You can apply paging to a gridview in two ways
(1) Use an object datasource with your gridview
(2) Use jquery Datatable

Creating DAL for ASP.NET website

I am working on Microsoft Visual Studio DAL in which I am doing the traditional method of fetching/updating the data to show the reviews of the listed items of website by retrieving data from the ItemDetails table of the website database, for creating the ItemDetails.aspx file. I added a DropDownList Control to displaying all items within its categories.
On selection of category from Drop-down list, it shows all items within that category, with a hyperlink attached "Show Details" to it to show details in a grid-view.
i am newbie i have no idea to create DAL for asp.net website. Need easy guidelines to create DAL for asp.net website. Help will be appreciated. What are the other ways to create DAL rather than SQLadapter.
So for example here is a DAL I've used before for calling SPs.
It allows you to execute stored procedures and return dataset, datatables, success responses etc.
Really it depends on how you intend to access the data, will you be writing Stored Procedures or will you have queries in your code. You also have the option of using Entity Framework/LINQ.
using System;
using System.Collections.Generic;
using System.Web;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Configuration;
public class _DataInteraction
{
#region "Stored Procedures"
public static DataTable stdReturnDataTableQuery(string procedureName, string db)
{
DataTable myDataTable;
SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[db].ConnectionString);
SqlCommand cmd = new SqlCommand();
SqlDataAdapter myDataAdapter = new SqlDataAdapter();
cmd.CommandText = procedureName;
cmd.CommandType = CommandType.Text;
cmd.Connection = myConnection;
//-----------------------------------------------------------------------
// make our datatable to return
//-----------------------------------------------------------------------
myDataTable = new DataTable();
//-----------------------------------------------------------------------
// fill the datatable with the stored procedure results
//-----------------------------------------------------------------------
try
{
myConnection.Open();
myDataAdapter.SelectCommand = cmd;
myDataAdapter.Fill(myDataTable);
}
catch (Exception ex)
{
//flag as error happened
throw ex;
}
finally
{
myConnection.Close();
if ((myDataAdapter != null))
myDataAdapter.Dispose();
if ((cmd != null))
cmd.Dispose();
}
return myDataTable;
}
// Return a datatable from the database
public static DataTable stdReturnDataTable(string procedureName, List<SqlParameter> myParameters, string db)
{
SqlConnection myConnection = default(SqlConnection);
SqlCommand myCommand = default(SqlCommand);
SqlDataAdapter myDataAdapter = default(SqlDataAdapter);
DataTable myDataTable = default(DataTable);
string connString = null;
// -----------------------------------------------------------------------
// create instance of connection
// -----------------------------------------------------------------------
connString = ConfigurationManager.ConnectionStrings[db].ConnectionString;
myConnection = new SqlConnection();
myConnection.ConnectionString = connString;
//-----------------------------------------------------------------------
// create instance of command and dataadapter
//-----------------------------------------------------------------------
myCommand = new SqlCommand(procedureName, myConnection);
myDataAdapter = new SqlDataAdapter(myCommand);
//-----------------------------------------------------------------------
// say its a stored procedure command
//-----------------------------------------------------------------------
myCommand.CommandType = CommandType.StoredProcedure;
//-----------------------------------------------------------------------
// add any parameters?
//-----------------------------------------------------------------------
if ((myParameters != null))
{
foreach (SqlParameter myParm in myParameters)
{
// add the parameter to the command
myCommand.Parameters.Add(myParm);
}
}
//-----------------------------------------------------------------------
// make our datatable to return
//-----------------------------------------------------------------------
myDataTable = new DataTable();
//-----------------------------------------------------------------------
// fill the datatable with the stored procedure results
//-----------------------------------------------------------------------
try
{
myConnection.Open();
myDataAdapter.Fill(myDataTable);
}
catch (Exception ex)
{
//flag as error happened
throw ex;
}
finally
{
myConnection.Close();
if ((myDataAdapter != null))
myDataAdapter.Dispose();
if ((myCommand != null))
myCommand.Dispose();
}
return myDataTable;
}
// Return a dataset from the database
public static DataSet stdReturnDataset(string procedureName, List<SqlParameter> myParameters, string db)
{
SqlConnection myConnection = default(SqlConnection);
SqlCommand myCommand = default(SqlCommand);
SqlDataAdapter myDataAdapter = default(SqlDataAdapter);
DataSet ds = new DataSet();
string connString = null;
//-----------------------------------------------------------------------
// create instance of connection
//-----------------------------------------------------------------------
connString = ConfigurationManager.ConnectionStrings[db].ConnectionString;
myConnection = new SqlConnection();
myConnection.ConnectionString = connString;
//-----------------------------------------------------------------------
// create instance of command and dataadapter
//-----------------------------------------------------------------------
myCommand = new SqlCommand(procedureName, myConnection);
myDataAdapter = new SqlDataAdapter(myCommand);
//-----------------------------------------------------------------------
// say its a stored procedure command
//-----------------------------------------------------------------------
myCommand.CommandType = CommandType.StoredProcedure;
//-----------------------------------------------------------------------
// add any parameters?
//-----------------------------------------------------------------------
if ((myParameters != null))
{
foreach (SqlParameter myParm in myParameters)
{
// add the parameter to the command
myCommand.Parameters.Add(myParm);
}
}
//-----------------------------------------------------------------------
// fill the datatable with the stored procedure results
//-----------------------------------------------------------------------
try
{
myConnection.Open();
myDataAdapter.Fill(ds);
}
catch (Exception ex)
{
//flag as error happened
throw ex;
}
finally
{
myConnection.Close();
if ((myDataAdapter != null))
myDataAdapter.Dispose();
if ((myCommand != null))
myCommand.Dispose();
}
return ds;
}
// Return success from a query from the database
public static bool db_NonQuerySuccessResponse(string strCommandText, List<SqlParameter> myParameters, string db)
{
SqlConnection SQLConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[db].ConnectionString);
SqlCommand SQLCommand = new SqlCommand();
DataSet ds = new DataSet();
string Value = "";
bool success = false;
try
{
SQLCommand.CommandText = strCommandText;
SQLCommand.CommandType = CommandType.StoredProcedure;
SQLCommand.Parameters.Clear();
if ((myParameters != null))
{
foreach (SqlParameter myParm in myParameters)
{
// add the parameter to the command
SQLCommand.Parameters.Add(myParm);
}
}
SQLCommand.Connection = SQLConnection;
SQLConnection.Open();
SQLCommand.ExecuteNonQuery();
SQLConnection.Close();
success = true;
}
catch (Exception ex)
{
success = false;
return success;
}
return success;
}
// General non query, no results no success
public static bool db_NonQuery(string strCommandText, List<SqlParameter> myParameters, string db)
{
SqlConnection SQLConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[db].ConnectionString);
SqlCommand SQLCommand = new SqlCommand();
DataSet ds = new DataSet();
try
{
SQLCommand.CommandText = strCommandText;
SQLCommand.CommandType = CommandType.StoredProcedure;
SQLCommand.Parameters.Clear();
if ((myParameters != null))
{
foreach (SqlParameter myParm in myParameters)
{
// add the parameter to the command
SQLCommand.Parameters.Add(myParm);
}
}
SQLCommand.Connection = SQLConnection;
SQLConnection.Open();
SQLCommand.ExecuteNonQuery();
SQLConnection.Close();
}
catch (Exception ex)
{
return false;
}
return true;
}
//// Execute scalar on db
//public static string db_Scalar(string strCommandText, ref List<SqlParameter> myParameters, string db)
//{
// SqlConnection SQLConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[db].ConnectionString);
// SqlCommand SQLCommand = new SqlCommand();
// string Value = "";
// SQLCommand.CommandText = strCommandText;
// SQLCommand.CommandType = CommandType.StoredProcedure;
// SQLCommand.Parameters.Clear();
// if ((myParameters != null))
// {
// foreach (SqlParameter myParm in myParameters)
// {
// // add the parameter to the command
// SQLCommand.Parameters.Add(myParm);
// }
// }
// SQLCommand.Connection = SQLConnection;
// SQLConnection.Open();
// Value = SQLCommand.ExecuteScalar;
// SQLConnection.Close();
// return Value;
//}
#endregion
}
Below is 1 sample for reference............
public List<T> GetRequests(string strNo)
{
List<T> objlstMapping = null;
Mapping objMapping = null;
try
{
Database objDbInstance = CreateSQLDatabase(DbConnection.MF);
using (DbCommand objDbCommand = objDbInstance.GetStoredProcCommand(Constants.SP_QUESTS))
{
DALBase.AddDbParam(objDbInstance, objDbCommand, "#No", DbType.AnsiString, ParameterDirection.Input, strFolioNo);
objDbCommand.Connection = objDbInstance.CreateConnection();
objDbCommand.Connection.Open();
using (DbDataReader dr = objDbCommand.ExecuteReader(CommandBehavior.CloseConnection))
{
objMapping = new List<T>();
if (dr.HasRows)
{
while (dr.Read())
{
objMapping = new BrokerFolioMapping();
objMapping .Brok_Code = SProposedValue(dr, "Code");
objMapping .Active = SProposedValue(dr, "Status");
objMapping .AccStmt_Active = SProposedValue(dr, "PortfolioStatus");
objlstFolioMapping.Add(objMapping );
}
}
}
}
}
catch (Exception ex)
{
}
return objlstFolioMapping;
}

Dataaccess help in three tier asp.net architecture

I have DAL function as
public DataTable executeSelectQuery(String _query, SqlParameter[] sqlParameter)
{
SqlCommand myCommand = new SqlCommand();
DataTable dataTable = new DataTable();
dataTable = null;
DataSet ds = new DataSet();
try
{
myCommand.Connection = openConnection();
myCommand.CommandText = _query;
myCommand.Parameters.AddRange(sqlParameter);
myCommand.ExecuteNonQuery();
myAdapter.SelectCommand = myCommand;
myAdapter.Fill(ds);
dataTable = ds.Tables[0];
}
catch (SqlException e)
{
Console.Write("Error - Connection.executeSelectQuery - Query:
" + _query + " \nException: " + e.StackTrace.ToString());
return null;
}
finally
{
}
return dataTable;
}
My button click
public void save_click(object sender,EventArgs e)
{
try
{
string query = "Insert into customer_master(customer_title,customer_name)values(#parameter1,#parameter2)";
SqlParameter[] sqlparam = new SqlParameter[2];
sqlparam[0] = new SqlParameter("#parameter1", SqlDbType.VarChar, 50);
sqlparam[0].Value = ddl_title.SelectedValue;
sqlparam[1] = new SqlParameter("#parameter2", SqlDbType.VarChar, 50);
sqlparam[1].Value = txt_group_name.Text;
string id = ms.insert(query, sqlparam);
catch(Exception ex)
{
throw ex;
}
}
I want the button click function values to passed not as sqlparameter but as sql command object.How to do this with sqlcommand object instead of sqlparameter.
Why do you want to pass around SqlCommand objects?? I wouldn't consider that an improvement of your current code - in the contrary!
Your UI code should really only pass values to the DAL function - just a List<int> or two strings or something. The DAL should do all the database-related stuff like creating SqlCommand and SqlParameters
So in your case here, I would have a method InsertCustomer on your DAL something like this:
public void InsertCustomer(string customerName, string customerTitle)
{
.... // do all the DB stuff here - create SqlCommand, fill in SqlParameter,
// execute the query
}
and your UI code should call this like this:
MyDAL dal = new MyDAL();
dal.InsertCustomer(txt_group_name.Text, ddl_title.SelectedValue);
There should be no trace whatsoever of ADO.NET classes or function in your UI code layer! So don't create SqlCommand or even SqlParameter in your UI layer - encapsulate this in the DAL layer! That what it's for!

how to write select parameterized query in asp.net

Below code is written to call parameterized select query in asp.net
public bool checkConflictTime()
{
bool TimeExists = false;
DataSet ds = new DataSet();
SqlConnection sqlconn = new SqlConnection();
sqlconn.ConnectionString = ConfigurationManager.ConnectionStrings["TestConn"].ConnectionString;
string sql = #"SELECT * FROM Images WHERE starttime= #starttime AND endtime = #endtime";
SqlCommand sqlcommand = new SqlCommand(sql,sqlconn);
//sqlcommand.Connection = sqlconn;
//string sql = "CheckConflictTimings";
sqlcommand.CommandType = CommandType.Text;
sqlcommand.CommandText = sql;
sqlcommand.Parameters.Add(new SqlParameter("#starttime", ddlStartTime.SelectedItem.Text));
sqlcommand.Parameters.Add(new SqlParameter("#endtime", ddlEndTime.SelectedItem.Text));
SqlDataAdapter da = new SqlDataAdapter(sql, sqlconn);
try
{
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
TimeExists = true;
}
}
catch (Exception ex)
{
}
finally
{
sqlconn.Close();
sqlconn.Dispose();
}
return TimeExists;
}
Is there something wrong? it threw error of :Must declare the scalar variable "#starttime"
when filling data adapter.
Try
SqlDataAdapter da = new SqlDataAdapter(sqlcommand);
Try
sqlcommand.Parameters.Add(new SqlParameter("starttime", ddlStartTime.SelectedItem.Text));
I don't think you need the # prefix when adding the parameter.
I think you're not passing your command as a SelectCommand to the adapter.
da.SelectCommand = sqlcommand;
Try
sqlcommand.Parameters.AddWithValue("#starttime",ddlStartTime.SelectedItem.Text);
instead of
sqlcommand.Parameters.Add(new SqlParameter("#starttime", ddlStartTime.SelectedItem.Text));

Resources