How to create table by giving width option? - c#

I am trying to create table.
Below is my code:
private void btnOK_Click(object sender, EventArgs e)
{
if (con.State == ConnectionState.Open) { con.Close(); }
con.Open();
string s = "CREATE TABLE ["+"" + rchtxtFieldCode.Text + "] "+ " (" + rchFieldTitle.Text + " " + combDataType.Text + "("+txtWidth.Text+")" + ")";
SqlCommand cmd = new SqlCommand(s, con);
if (cmd.ExecuteNonQuery() >= 1)
{
MessageBox.Show("created");
}
con.Close();
}
It is creating table. But, it is showing exception when the datatype is int or text.
I want every datatype to function properly.

Try this
string width = string.IsNullOrEmpty(txtWidth.Text.Trim()) ? string.Empty : "(" + txtWidth.Text.Trim() + ")"
string s = "CREATE TABLE [" + "" + rchtxtFieldCode.Text + "] " + " (" + rchFieldTitle.Text + " " + combDataType.Text + width + ")";

Related

Error with SQL Server request using data.sqlclient in UWP

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 + "%'";

Unable to cast object of type 'Obout.Grid.GridTemplate' to type 'System.Web.UI.WebControls.GridViewRow'. not resolving

I want to disable gridview row on button click which is inside the gridview. So for that I have written the below code.
protected void btnPayGenInvoice_Click(object sender, EventArgs e)
{
if (strMode == "M")
{
Button btn = (Button)sender;
GridViewRow row = (GridViewRow)btn.Parent.Parent;
row.Enabled = false;
}
}
But I am getting error as
Unable to cast object of type 'Obout.Grid.GridTemplate' to type 'System.Web.UI.WebControls.GridViewRow'.
kindly let me know what is wrong here
UPDATE
Getting error at line GridViewRow row = (GridViewRow)btn.Parent.Parent;
update 2
Code for button click event.
protected void GetRowDataPay(object sender, CommandEventArgs e)
{
int rowIndex = int.Parse(e.CommandArgument.ToString());
Hashtable dataItemPay = GridPayInfo.Rows[rowIndex].ToHashtable() as Hashtable;
if (ObjPriCon.State != ConnectionState.Open)
{
ObjPriCon.Open();
OracleCommand cmdMkeyPay = new OracleCommand("select XXCUS.XXACL_LAND_PURC_INV_VIEW_MKEY.nextval from dual", ObjPriCon);
string MkeyPay = Convert.ToString(cmdMkeyPay.ExecuteOracleScalar());
OracleCommand cmdORGID = new OracleCommand("select XXCUS.XXACL_LAND_PURC_INV_VIEW_MKEY.nextval from dual", ObjPriCon);
string ORG_IDKEY = CF.ExecuteScaler2("select ORGANIZATION_ID,ORGANIZATION_NAME from apps.xxacl_company_mst where ORGANIZATION_NAME = '" + txtCompName.Value + "'");
string strExpQuery = "insert into XXCUS.XXACL_LAND_PURC_INVOICE_VIEW (MKEY,REF_PURCHASE_ID,REF_SR_NO, " +
"REF_PURHCASE_TYPE,ORG_ID,PROJECT_ID,TALUKA_ID,VILLAGE_ID,SURVEY_AREA_7_12,DOC_NO,INVOICE_ID,INVOICE_NUM,VENDOR_ID, " +
"VENDOR_NAME,INVOICE_AMT,BATCH_ID,BATCH_NAME,EXP_ID,EXP_TYPE,REMARKS,CREATED_BY, " +
"CREATION_DATE,LAST_UPDATE_DATE,LAST_UPDATED_BY, EXP_ORG_ID, EXP_ORG_NAME) values (" + MkeyPay + "," + StrMkey + "," +
"" + dataItemPay["SR_NO"] + ", '" + dataItemPay["ATTRIBUTE1"] + "'," + ORG_IDKEY + "," + ddlProject.SelectedValue + "," +
"" + ddlTaluka.SelectedValue + "," + ddlVillage.SelectedValue + ", '" + txt712.Text + "', '" + txtdocno.Value + "'," + "NULL" + "," + "NULL" + "," +
"" + dataItemPay["ORACLE_VENDOR_ID"] + ", '" + dataItemPay["ORACLE_VEND_NAME"] + "', " + dataItemPay["PAID_AMT"] + "," + dataItemPay["BATCH_ID"] + "," +
"'" + dataItemPay["BATCH_NAME"] + "', " + dataItemPay["EXP_ID"] + ", '" + dataItemPay["EXP_TYPE"] + "', '" + dataItemPay["REMARKS"] + "', " +
"" + Request.QueryString["userid"].ToString() + ", sysdate, sysdate, " +
"'" + Request.QueryString["userid"].ToString() + "', " + "NULL" + "," + "NULL" + ")";
OracleCommand cmdQuery = new OracleCommand(strExpQuery, ObjPriCon);
cmdQuery.ExecuteNonQuery();
ObjPriCon.Close();
ScriptManager.RegisterStartupScript(this, this.GetType(), "Success", "alert('Payment Invoice inserted into table successfully');", true);
}
}
You should use the rowIndex value to get the gridviewrow and then disable it something like this
if (GridPayInfo.Rows[rowIndex] != null)
{
GridPayInfo.Rows[rowIndex].Enabled = false;
}

XSS and SQL Injection threats found by AppScan Source

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.

how to create a table having spaces between the words?

I am trying to create a table using code.
Here is my code.
private void btnOK_Click(object sender, EventArgs e)
{
if (con.State == ConnectionState.Open) { con.Close(); }
con.Open();
string s = "CREATE TABLE "+"" + rchtxtFieldCode.Text + " "+ " (" + rchFieldTitle.Text + " " + combDataType.Text + "" + ")";
SqlCommand cmd = new SqlCommand(s, con);
if (cmd.ExecuteNonQuery() >= 1)
{
MessageBox.Show("created");
}
con.Close();
}
It is creating the table if the table name has single word.. It is showing exception if there is space between the words(eg: Sales Info)
If this is for SQL Server you use square brackets:
string s = "CREATE TABLE ["+"" + rchtxtFieldCode.Text + "] "+ " ([" + rchFieldTitle.Text + "] " + combDataType.Text + "" + ")";
In fact you should always use square brackets to stop these kind of errors happening.
Also ensure you are sanitising your strings otherwise you might have SQL injection issues.
Just add Box braces:
string s = "CREATE TABLE ["+"" + rchtxtFieldCode.Text + "] "+ " (" + rchFieldTitle.Text + " " + combDataType.Text + "" + ")";
//^_______________________________^
Do not use spaces in table or field names.In this, Try to change query with Square brackets i.e.
For example ,
sqlString = "CREATE TABLE [All Students]"
use this code, i think it will give you the desire output.
private void btnOK_Click(object sender, EventArgs e)
{
if (con.State == ConnectionState.Open) { con.Close(); }
con.Open();
string s = "CREATE TABLE '"+rchtxtFieldCode.Text + "'(" +"'"+rchFieldTitle.Text +"'" + combDataType.Text + "" + ")";
SqlCommand cmd = new SqlCommand(s, con);
if (cmd.ExecuteNonQuery() >= 1)
{
MessageBox.Show("created");
}
con.Close();
}

C# adding every table row to textbox from database

I've been working a bit with binding database tables to text boxes and I've encountered a problem. The code I have here gets all the columns I need from the table, but only 1 row's worth of data shows up. Is there a simple way to make every single row from the table appear in a text box? Or some other sort of text list?
SqlConnection cn = new SqlConnection("SERVER=myserver;DATABASE=mydb;Trusted_Connection=True");
SqlCommand cmd = new SqlCommand();
SqlDataReader dr = null;
cmd.Connection = cn;
cn.Open();
cmd.CommandText = "SELECT DisasterID,DisasterType,Location,CurrentStatus,IntensityLevel,Latitude,Longitude FROM Disasters";
dr = cmd.ExecuteReader();
if (dr.Read()) {
txtFeeds.Text = dr["DisasterID"].ToString() + " " + dr["DisasterType"].ToString() + " " + dr["Location"].ToString() + " " + dr["CurrentStatus"].ToString() + " " + dr["IntensityLevel"].ToString() + " " + dr["Latitude"].ToString() + " " + dr["Longitude"].ToString();
}
cn.Close();
You need while loop and append each line to textbox by txtFeeds.Text +=
while(dr.Read()) {
txtFeeds.Text += dr["DisasterID"].ToString() + " "
+ dr["DisasterType"].ToString() + " "
+ dr["Location"].ToString() + " "
+ dr["CurrentStatus"].ToString() + " "
+ dr["IntensityLevel"].ToString() + " "
+ dr["Latitude"].ToString() + " " + dr["Longitude"].ToString();
}
If you need more performance you can use StringBuilder to append text and finally set textbox text using StringBuilder.ToString method.
Edit.
StringBuilder sb = new StringBuilder();
while (dr.Read())
{
sb.AppendLine(dr["DisasterID"].ToString() + " "
+ dr["DisasterType"].ToString() + " "
+ dr["Location"].ToString() + " "
+ dr["CurrentStatus"].ToString() + " "
+ dr["IntensityLevel"].ToString() + " "
+ dr["Latitude"].ToString() + " " + dr["Longitude"].ToString());
}
txtFeeds.Text = sb.ToString();
First of all its a bad idea trying display records from a table in a single textbox.
If you still want to do it,
Use a while loop instead of IF condition
while(dr.Read())
{
}
Use a string builder and append all your column values to it and after while loop exists use the values in the string builder and set it to the field.
StringBuilder values = new StringBuilder();
while(dr.Read()) {
values.Append( dr["DisasterID"].ToString() + " " + dr["DisasterType"].ToString() + " " + dr["Location"].ToString() + " " + dr["CurrentStatus"].ToString() + " " + dr["IntensityLevel"].ToString() + " " + dr["Latitude"].ToString() + " " + dr["Longitude"].ToString());
}
txtFeeds.Text = values.ToString();

Categories