private static IEnumerable<string> getExtrato(string query)
{
using (var cn = new SqlConnection("Data Source=MAD-PC-023\\SQLEXPRESS;Database=bank;Trusted_Connection=True;"))
{
cn.Open();
using (var cmd = new SqlCommand() { Connection = cn, CommandText = query })
{
var reader = cmd.ExecuteReader();
var result = new List<string>();
while (reader.Read() == true && result.Count <= 9 )
{
if (reader.GetString(1) == "0")
{ //+ "ficando assim com: " + reader.GetDecimal(3)
result.Add("\n O cartão nº " + reader.GetString(0) + " levantou: " + reader.GetString(2) + " euros, " + " às: " + reader.GetDateTime(3));
}
else
{
result.Add("\n O cartão nº " + reader.GetString(0) + " depositou: " + reader.GetString(1) + " euros, " + " às: " + reader.GetDateTime(3));
}
}
return result;
}
}
}
private static IEnumerable<string> extratoOperacao(string numeroCartao)
{
return getExtrato($#"SELECT CardNumber, Deposit, Withdraw, DataHora FROM MoveInfo WHERE CardNumber = '{numeroCartao}'");
}
As I have is presenting me only the first 10 lines, but I need the last 10 by normal order, how do I do that?
If anyone can help me, I'd be grateful
private static IEnumerable<string> getExtrato(string query)
{
using (var cn = new SqlConnection("Data Source=MAD-PC-023\\SQLEXPRESS;Database=bank;Trusted_Connection=True;"))
{
cn.Open();
using (var cmd = new SqlCommand() { Connection = cn, CommandText = query })
{
var reader = cmd.ExecuteReader();
var result = new List<string>();
// Let's remove unused conditions
while (reader.Read())
{
if (reader.GetString(1) == "0")
{
result.Add("\n O cartão nº " + reader.GetString(0) + " levantou: " + reader.GetString(2) + " euros, " + " às: " + reader.GetDateTime(3));
}
else
{
result.Add("\n O cartão nº " + reader.GetString(0) + " depositou: " + reader.GetString(1) + " euros, " + " às: " + reader.GetDateTime(3));
}
}
// HERE IS THE MAGIC
return result.TakeLast(10);
}
}
}
If you use an ORDER BY in the query you can make sure which records are returned, and you can use TOP to restrict the quantity of records returned, so something like
return getExtrato($#"SELECT TOP 10 [CardNumber], [Deposit], [Withdraw], [DataHora], [Id] FROM [MoveInfo] WHERE [CardNumber] = '{numeroCartao}' ORDER BY [Id] DESC");
will return the desired records, and then you just need to read all of them and reverse the result in your code (there are other possibilities, but that might be simplest for now).
Related
Right now this is just presenting a line of the database but I need to present more, if anyone knew how to help me i would be grateful
private static string extratoOperacao(string numeroCartao)
{
return getExtrato($#"SELECT CardNumber, Deposit, Withdraw, DataHora FROM MoveInfo WHERE CardNumber = '{numeroCartao}'");
}
private static string getExtrato(string query)
{
using (var cn = new SqlConnection("Data Source=MAD-PC-023\\SQLEXPRESS;Database=bank;Trusted_Connection=True;"))
{
cn.Open();
using (var cmd = new SqlCommand() { Connection = cn, CommandText = query })
{
var reader = cmd.ExecuteReader();
while (reader.Read() == true)
{
if (reader.GetString(1) == null)
{
return "\n O cartão nº " + reader.GetString(0) + " levantou: " + reader.GetString(2) + " às: " + reader.GetDateTime(3);
}
else
{
return "\n O cartão nº " + reader.GetString(0) + " depositou: " + reader.GetString(1) + " euros " + " às: " + reader.GetDateTime(3);
}
}
return "";
}
}
}
The supposed is to show all the information of the lines where the card number is equal to the inserted
The return statement is going to exit your function, which is why you only get one result. If you want multiple lines, you're going to need to build and return a collection (e.g., array, list, etc.) or use yield return . . . the collection is probably the most straight-forward approach.
If you want all of the results in a single string, you'll need StringBuilder.
I have made a windows service in C# and while running the code, its giving the excpetion
Operation not valid due to current state of object
on ExecuteNOnQuery line. I have used similar code before but haven't faced this issue.
public void CCP_to_WRM()
{
DBConnection.Open_Connection();
//Reading data from CCP Table in Gateway PC
String sql = "select HEAT_NAME,STEEL_GRADE_ID,PRODUCTION,BILLET_STATUS,CASTER_NO from CCP_BILLET";
DBConnection.ComndCCP.CommandText = sql;
DBConnection.ComndCCP.ExecuteNonQuery(); //--> Exception occurs here.
OracleDataReader ReadWRM = DBConnection.ComndCCP.ExecuteReader();
while (ReadWRM.Read())
{
HeatId = ReadWRM[0].ToString().TrimEnd();
StGr = ReadWRM[1].ToString().TrimEnd();
BillN = int.Parse(ReadWRM[2].ToString().TrimEnd());
BS = int.Parse(ReadWRM[3].ToString().TrimEnd());
CsNo = int.Parse(ReadWRM[4].ToString().TrimEnd());
//Inserting data from CCP into Mills DB
int i = 0;
int LayerNo = 0;
int BilletId = 0;
int BilletSeq = 0;
int RowCount = 0;
//string sqlD = "delete from stg_billet where heat_id='" + InHeat + "'";
//DBConnection.ComndWRM.CommandText = sqlD;
//DBConnection.ComndWRM.ExecuteNonQuery();
string sql1 = "select layer_no from stg_bil_layer order by layer_no asc";
DBConnection.ComndWRM.CommandText = sql1;
DBConnection.ComndWRM.ExecuteNonQuery();
OracleDataReader ReadLayer = DBConnection.ComndWRM.ExecuteReader();
while (ReadLayer.Read())
{
LayerNo = int.Parse(ReadLayer[0].ToString().TrimEnd());
}
LayerNo++;
//DialogResult result2 = MessageBox.Show("Inserting"+LayerNo);
string sql2 = "insert into stg_bil_layer values ('1','BOX1'," + LayerNo + ",'SQUARE 150X150'," + BillN + "," + 0 + ",'"
+ StGr + "','" + HeatId + "'," + 2100 + "," + 12000 + "," + "'CASTER'," + "'CASTER'," + "'CASTER'," + "'$SNT',sysdate)";
//to_date('"+DateTime.Now.ToString("DD/MM/YYYY")+"','DD/MM/YYYY')
DBConnection.ComndWRM.CommandText = sql2;
int RowS = DBConnection.ComndWRM.ExecuteNonQuery();
if (RowS >= 1)
{
//DialogResult result3 = MessageBox.Show("Record Inserted !!!!"+RowS);
string sql3 = "select billet_id from stg_billet order by billet_id asc";
DBConnection.ComndWRM.CommandText = sql3;
DBConnection.ComndWRM.ExecuteNonQuery();
OracleDataReader ReadBI = DBConnection.ComndWRM.ExecuteReader();
while (ReadBI.Read())
{
BilletId = int.Parse(ReadBI[0].ToString().TrimEnd());
//BilletSeq = int.Parse(ReadBI[1].ToString().TrimEnd());
}
sql3 = "select billet_seq from stg_billet order by billet_seq asc";
DBConnection.ComndWRM.CommandText = sql3;
DBConnection.ComndWRM.ExecuteNonQuery();
OracleDataReader ReadBS = DBConnection.ComndWRM.ExecuteReader();
while (ReadBS.Read())
{
//BilletId = int.Parse(ReadBI[0].ToString().TrimEnd());
BilletSeq = int.Parse(ReadBS[0].ToString().TrimEnd());
}
//DialogResult result4 = MessageBox.Show("Bilet ID " + BilletId+'\n'+"Billet Sequence "+BilletSeq);
for (i = 0; i < BillN; i++)
{
//DialogResult result1 = MessageBox.Show("Inside Loop");
BilletId++;
BilletSeq++;
string sql4 = "insert into stg_billet values (" + BilletId + "," + BilletSeq + ","
+ 1 + ",'BOX1'," + LayerNo + "," + CsNo + ","
+ 1 + ",'" + HeatId + "'," + "'PLAN' " + ",'" + StGr + "'," + "'1234567890',"
+ 0 + ",sysdate,sysdate," + 0 + "," + 3 + "," + 1 + "," + 150 + "," + 150 + "," + 12000 + "," + 2100 + ","
+ 3 + "," + 1 + "," + 10 + "," + "'$SNT',sysdate)";
DBConnection.ComndWRM.CommandText = sql4;
int RowB = DBConnection.ComndWRM.ExecuteNonQuery();
RowCount = RowCount + RowB;
}
/*
if (RowCount >= 1)
{
DialogResult result1 = MessageBox.Show("Record Inserted !!!!" + '\n' + RowCount + " Billets");
}
DBConnection.Close_Connection();
this.Hide();
Form2 f2 = new Form2();
f2.ShowDialog();
*/
}
/*
else
{
DialogResult result4 = MessageBox.Show("Failed to Insert !!!!" + RowS);
DBConnection.Close_Connection();
this.Hide();
Form2 f2 = new Form2();
f2.ShowDialog();
}
*/
}
DBConnection.Close_Connection();
}
I have used a DBConnection class for making connection to the database(DBConnection).
I have even tried making connection in the same script but it didn't work.
I am trying to run a SQL query on my UWP code. I don't use Linq or EF. The connection to the base work and the simple requests work. This causes me problems: in a first time i populate a listview with the result of a simple request, i choose an element and i click on a searchin button. This request is call with an error:
static public ObservableCollection GetGaz(string connectionString,
string selectedOrder)
{
string GetGazQuery =
"SELECT " +
"tbl_607_gaz_type.gaz_type," +
"tbl_607_theorical_content.theorical_content," +
"tbl_607_made_tolerance.made_tolerance," +
"tbl_607_order_details.gaz_lifetime," +
"tbl_607_gaz.gaz_comments," +
"tbl_607_order_details.FK_ID_order," +
"tbl_607_order_details.poste_number, " +
"tbl_607_order.order_number" +
"FROM " +
"tbl_607_provider join tbl_607_order on tbl_607_provider.ID = tbl_607_order.FK_ID_provider " +
"join tbl_607_order_details on tbl_607_order.ID = tbl_607_order_details.FK_ID_order" +
"join tbl_607_gaz on tbl_607_order_details.FK_ID_gaz = tbl_607_gaz.ID " +
"join tbl_607_gaz_type on tbl_607_gaz.FK_ID_gaz_type = tbl_607_gaz_type.ID " +
"join tbl_607_made_tolerance on tbl_607_gaz.FK_ID_made_tolerence = tbl_607_made_tolerance.ID " +
"join tbl_607_theorical_content on tbl_607_gaz.FK_ID_theorical_content = tbl_607_theorical_content.ID " +
"WHERE " +
"tbl_607_order.order_number" + " LIKE " + "'%" + selectedOrder + "%'";
ObservableCollection GazList = new ObservableCollection();
try
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
if (conn.State == System.Data.ConnectionState.Open)
{
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = GetGazQuery;
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Gaz gaz = new Gaz
{
Gaz_type = reader.GetString(0),
Theorical_content = reader.GetString(1),
Made_tolerance = reader.GetDouble(2),
Gaz_lifetime = reader.GetInt32(3),
Gaz_comments = reader.GetString(4),
Poste_number = reader.GetInt32(6)
};
GazList.Add(gaz);
}
}
}
}
}
return GazList;
}
catch (Exception eSql)
{
Debug.WriteLine("Exception: " + eSql.Message);
}
return null;
}
}
private string selectedOrder;
public Gestion_Stock()
{
this.InitializeComponent();
SelectOrders.ItemsSource = OrdersDataHelper.GetOrders(connectionString: (Windows.UI.Xaml.Application.Current as App).ConnectionString);
}
private void Search_Click(object sender, RoutedEventArgs e)
{
Affichage_Stock_Gaz.ItemsSource = GazDataHelper.GetGaz((Windows.UI.Xaml.Application.Current as App).ConnectionString, selectedOrder);
}
private void SelectOrders_SelectionChanged (object sender, SelectionChangedEventArgs e)
{
ListView selectOrders = sender as ListView;
Orders orders = SelectOrders.SelectedItem as Orders;
selectedOrder = orders.Order_Number;
}
The output:
Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.SqlClient.dll
Exception: Incorrect syntax near the keyword 'join'
This simple request is working, i don't use a variable and "where" command.
This work:
static public ObservableCollection GetOrders(string connectionString)
{
const string GetOrdersQuery = "" +
"select " +
"tbl_607_order.start_date," +
"tbl_607_order.end_date," +
"tbl_607_provider.provider_name," +
"tbl_607_order.order_number," +
"tbl_607_order.shipping_request_active," +
"tbl_607_order.item_reception_active " +
"from " +
"tbl_607_provider join tbl_607_order on tbl_607_provider.ID = tbl_607_order.FK_ID_provider "
;
Someone would have any idea?
Thanks a lot!
Add the missing space by changing
"SELECT " +
"tbl_607_gaz_type.gaz_type," +
"tbl_607_theorical_content.theorical_content," +
"tbl_607_made_tolerance.made_tolerance," +
"tbl_607_order_details.gaz_lifetime," +
"tbl_607_gaz.gaz_comments," +
"tbl_607_order_details.FK_ID_order," +
"tbl_607_order_details.poste_number, " +
"tbl_607_order.order_number" +
"FROM " +
"tbl_607_provider join tbl_607_order on tbl_607_provider.ID = tbl_607_order.FK_ID_provider " +
"join tbl_607_order_details on tbl_607_order.ID = tbl_607_order_details.FK_ID_order" +
"join tbl_607_gaz on tbl_607_order_details.FK_ID_gaz = tbl_607_gaz.ID " +
"join tbl_607_gaz_type on tbl_607_gaz.FK_ID_gaz_type = tbl_607_gaz_type.ID " +
"join tbl_607_made_tolerance on tbl_607_gaz.FK_ID_made_tolerence = tbl_607_made_tolerance.ID " +
"join tbl_607_theorical_content on tbl_607_gaz.FK_ID_theorical_content = tbl_607_theorical_content.ID " +
"WHERE " +
"tbl_607_order.order_number" + " LIKE " + "'%" + selectedOrder + "%'";
to
"SELECT " +
"tbl_607_gaz_type.gaz_type," +
"tbl_607_theorical_content.theorical_content," +
"tbl_607_made_tolerance.made_tolerance," +
"tbl_607_order_details.gaz_lifetime," +
"tbl_607_gaz.gaz_comments," +
"tbl_607_order_details.FK_ID_order," +
"tbl_607_order_details.poste_number, " +
"tbl_607_order.order_number" +
"FROM " +
"tbl_607_provider join tbl_607_order on tbl_607_provider.ID = tbl_607_order.FK_ID_provider " +
"join tbl_607_order_details on tbl_607_order.ID = tbl_607_order_details.FK_ID_order " + // note the missing space added here
"join tbl_607_gaz on tbl_607_order_details.FK_ID_gaz = tbl_607_gaz.ID " +
"join tbl_607_gaz_type on tbl_607_gaz.FK_ID_gaz_type = tbl_607_gaz_type.ID " +
"join tbl_607_made_tolerance on tbl_607_gaz.FK_ID_made_tolerence = tbl_607_made_tolerance.ID " +
"join tbl_607_theorical_content on tbl_607_gaz.FK_ID_theorical_content = tbl_607_theorical_content.ID " +
"WHERE " +
"tbl_607_order.order_number" + " LIKE " + "'%" + selectedOrder + "%'";
My code seems correct. But when I add the Group keyword in the query it produces a message:
Incorrect syntax near the keyword 'Group'
but when I remove the Group keyword the program runs successfully.
private void CSRMaintReviewer_Load(object sender, EventArgs e)
{
this.MaintReviewertbl.DataSource = null;
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["csrapps"].ConnectionString);
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select " +
"EmailID_Reviewer, " +
"Reviewer_Name, " +
"Reviewer_Email, " +
"EmailID_TeamLead, " +
"TeamLead_Name, " +
"TeamLead_Email, " +
"Site, " +
"Business_Unit, " +
"Group, " +
"Station, " +
"Pkg_Department, " +
"Region, " +
"Account, " +
"Key_Field, " +
"EmailID_SiteManager, " +
"SiteManager_Name, " +
"SiteManager_Email, " +
"EmailID_SiteDirector, " +
"SiteDirector_Name, " +
"SiteDirector_Email, " +
"EmailID_President, " +
"President_Name, " +
"President_Email, " +
"Customer, " +
"Flag, " +
"CreatedBy, " +
"DateCreated, " +
"LastUpdatedBy, " +
"DateUpdated " +
"from dbo.tblCSRMaintReviewer ";
try
{
SqlDataReader reader = null;
reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
MaintReviewer reviewer = new MaintReviewer();
reviewer.EmailIDReviewer = reader["EmailID_Reviewer"].ToString();
reviewer.ReviewerName = reader["Reviewer_Name"].ToString();
reviewer.ReviewerEmail = reader["Reviewer_Email"].ToString();
reviewer.EmailIDTeamLead = reader["EmailID_TeamLead"].ToString();
reviewer.TeamLeadName = reader["TeamLead_Name"].ToString();
reviewer.TeamLeadEmail = reader["TeamLead_Email"].ToString();
reviewer.Site = reader["Site"].ToString();
reviewer.BusinessUnit = reader["Business_Unit"].ToString();
reviewer.Group = reader["Group"].ToString();
reviewer.Station = reader["Station"].ToString();
reviewer.PKGDepartment = reader["Pkg_Department"].ToString();
reviewer.Region = reader["Region"].ToString();
reviewer.Account = reader["Account"].ToString();
reviewer.KeyField = reader["Key_Field"].ToString();
reviewer.EmailIDSiteManager = reader["EmailID_SiteManager"].ToString();
reviewer.SiteManagerName = reader["SiteManager_Name"].ToString();
reviewer.SiteManagerEmail = reader["SiteManager_Email"].ToString();
reviewer.EmailIDSiteDirector = reader["EmailID_SiteDirector"].ToString();
reviewer.SiteDirectorName = reader["SiteDirector_Name"].ToString();
reviewer.SiteDirectorEmail = reader["SiteDirector_Email"].ToString();
reviewer.EmailIDPresident = reader["EmailID_President"].ToString();
reviewer.PresidentName = reader["President_Name"].ToString();
reviewer.PresidentEmail = reader["President_Email"].ToString();
reviewer.Customer = reader["Customer"].ToString();
reviewer.Flag = reader["Flag"].ToString();
reviewer.CreatedBy = reader["CreatedBy"].ToString();
reviewer.DateCreated = reader["DateCreated"].ToString();
reviewer.LastUpdatedBy = reader["LastUpdatedBy"].ToString();
reviewer.DateUpdated = reader["DateUpdated"].ToString();
string[] row = { reviewer.EmailIDReviewer, reviewer.ReviewerName, reviewer.ReviewerEmail, reviewer.EmailIDTeamLead, reviewer.TeamLeadName,
reviewer.TeamLeadEmail, reviewer.Site, reviewer.BusinessUnit, reviewer.Group, reviewer.Station, reviewer.PKGDepartment,
reviewer.Region, reviewer.Account, reviewer.KeyField, reviewer.EmailIDSiteManager, reviewer.SiteManagerName,
reviewer.SiteManagerEmail, reviewer.EmailIDSiteDirector, reviewer.SiteDirectorName, reviewer.SiteDirectorEmail, reviewer.EmailIDPresident,
reviewer.PresidentName, reviewer.PresidentEmail, reviewer.Customer, reviewer.Flag, reviewer.CreatedBy,
reviewer.DateCreated, reviewer.LastUpdatedBy, reviewer.DateUpdated };
reviewers.Add(reviewer);
}
MaintReviewertbl.DataSource = reviewers;
MaintReviewertbl.Refresh();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
conn.Dispose();
cmd.Dispose();
}
}
Its giving you an error because Group is a keyword(words that have a special meaning in SQL like Select and from). This Group is conflicting with Group By and you are using it as a column name. You should change your column name in the table to something like Groupname or GroupType anything that is not a keyword in SQL. This will solve the error.
Looks like you are having a column named Group, but it's a keyword So I suggest you to change the column name(if it will not need severe coding changes) or else simply enclose them in a pair of [], like this [Group]. Keep in mind its not a good practice to give such keywords for other purposes, they are already reserved for some other purposes
So I have been given administration on a website that is basically a company conference room reservation system, it is connected to an access database for room details and vacancies. Problem is, AppScan source is showing a risk of XSS and SQL Injection. This is the complete function in where it is indicating the occurrence of these errors.
protected void btnReserve_Click(object sender, System.EventArgs e)
{
string start_slot, end_slot, event_desc, room_id, emp_nid;
string[] date;
start_slot = ddlStart.SelectedValue;
end_slot = ddlEnd.SelectedValue;
event_desc = txtEventDesc.Text;
room_id = Server.HtmlEncode(Request.QueryString["room_id"]);
emp_nid = Regex.Replace(Request.ServerVariables["LOGON_USER"], #"^.*\\(.*)$", "$1").ToUpper();
date = Request.QueryString["date"].Split('/');
DateTime dt = new DateTime(Convert.ToInt32(date[2]),Convert.ToInt32(date[0]),Convert.ToInt32(date[1]));
string sCmdCheckConflict = #"
SELECT count(*)
FROM t_msc_event
WHERE (event_date = #" +DateTime.Parse(Request.QueryString["date"]).ToString() + #"# )
AND (room_id = " + room_id + #") AND
(
(" + start_slot + #" BETWEEN start_slot AND end_slot) OR
(" + end_slot + #" BETWEEN start_slot AND end_slot) OR
(start_slot BETWEEN " + start_slot + #" AND " + end_slot + #") OR
(end_slot BETWEEN " + start_slot + #" AND " + end_slot + "))";
OleDbCommand cmdConflictCounter = new OleDbCommand(sCmdCheckConflict, cn);
int n;
int event_id;
try
{
cn.Open();
n = (int) cmdConflictCounter.ExecuteScalar();
string Msg;
if (n>0)
{
Msg = "<script language=javascript>alert('Chosen time is not possible due to a conflict.');</script>";
}
else
{
#region MS Access related region
OleDbCommand cmdgetMaxId = new OleDbCommand("select max(event_id) from t_msc_event", cn);
string sCmdInsert;
OleDbCommand cmdInsertEvent = null;
event_id = 0; bool success = false; int trials = 0;
do
{
try
{
event_id = (int) cmdgetMaxId.ExecuteScalar() + 1;
}
catch
{
event_id = 0;
}
sCmdInsert = #"
insert into t_msc_event (event_id,
emp_nid, event_desc, event_date,
start_slot, end_slot, room_id
) values (" + event_id + #",
'" + Server.HtmlEncode(emp_nid) + "', '" + Server.HtmlEncode(event_desc.Replace("'", "''")) + "', #" + dt.ToShortDateString() + "#, " +
start_slot + ", " + end_slot + ", " + room_id + ")";
cmdInsertEvent = new OleDbCommand(sCmdInsert, cn);
cmdInsertEvent.ExecuteNonQuery();
success = true;
} while ((!success) && (trials <=5));
OleDbDataAdapter daGetSlots = new OleDbDataAdapter("select slot_id, left(slot_desc,5) as slot_start, right(slot_desc,5) as slot_end from t_msc_slot order by slot_id", cn);
DataTable dtSlotInfo = new DataTable();
daGetSlots.Fill(dtSlotInfo);
OleDbCommand cmdGetRoolTitle = new OleDbCommand("select room_title from t_msc_room where room_id=" + Server.HtmlEncode(room_id), cn);
string room_title = (string) cmdGetRoolTitle.ExecuteScalar();
string msg = "Dear " + emp_nid +
",<br><br>This is to confirm your reservation of " +
room_title +
" on " + dt.ToShortDateString() + " from " +
dtSlotInfo.Rows[Convert.ToInt32(start_slot)]["slot_start"].ToString() + " to " +
dtSlotInfo.Rows[Convert.ToInt32(end_slot)]["slot_end"].ToString() + "." +
"<br><br>In case you want to cancel, go to " +
"<a href='" + Regex.Replace(Request.Url.ToString(), #"^(.*)/.*\.aspx\?*.*$", "$1/MyReservations.aspx") + "'>" +
"MS Conference Rooms Reservation -> MyReservatios</a>";
#endregion
string subject = "MS Conference Room Reservation Confirmation [id=" + event_id + "]";
try
{
SendEmail(emp_nid, subject, msg);
Msg = "<script language=javascript>alert('Room successfully reserved. You should receive a confirmation email shortly.'); if (opener) {opener.__doPostBack('" + Request.QueryString["btnGetScheduleID"].Replace("_","$") + "', '');} window.close();</script>";
}
catch
{
Msg = "<script language=javascript>alert('Room successfully reserved.'); if (opener) {opener.__doPostBack('" + Request.QueryString["btnGetScheduleID"].Replace("_","$") + "', '');} window.close();</script>";
}
}
Response.Write(Msg);
}
catch (Exception x)
{
Response.Write(x.ToString());
string Msg;
Msg = "<script language=javascript>alert('Error: " + x.ToString() + "');</script>";
Response.Write(Msg);
}
finally
{
cn.Close();
}
}
Sorry for having to show you the whole function as I have really no idea what I need to do here, this isn't my app.
what I did do is 1) Enable Request Validation in ASP.NET 2) encode user input by using Server.HtmlEncode(); but it is still reporting the same thing. Note that both start_slot and end_slot are DDLs so I thought I wouldn't need to encode/check them before sending. Would you please help me in modifying this code to neglect harmful user input? Thank you loads.
The correct way to use parameterized SQL query is
string commandText = "UPDATE ProductDetails
SET ProductQuantity = #quantity WHERE ProductId = #productId";
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.AddWithValue("#productId", "P123");
command.Parameters.AddWithValue("#quantity", 10);
You can safely replace the "P123" with user provided input now.