Insert data into local SQL Server database from ASP.NET - c#

I am trying to insert data from ASP.NET into a local SQL Server database. I am following from https://www.youtube.com/watch?v=8bNCfUaJPf8. maybe you can try to watch the video first. I am following exactly same for the process.
Here is the code :
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.auto-style1 {
text-align: center;
}
.auto-style2 {
width: 100%;
}
.auto-style3 {
width: 183px;
}
.auto-style4 {
width: 183px;
height: 21px;
}
.auto-style5 {
height: 21px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 class="auto-style1">insert data</h2>
<br />
</div>
<table class="auto-style2">
<tr>
<td class="auto-style4">FirstName :</td>
<td class="auto-style5">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style3">LastName :</td>
<td>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style3">City :</td>
<td>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style3"> </td>
<td>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" />
</td>
</tr>
</table>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" OnSelecting="SqlDataSource1_Selecting" SelectCommand="SELECT * FROM [Table]"></asp:SqlDataSource>
</form>
</body>
</html>
Here is the code-behind file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
con.Open();
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("insert into Table (fname, lname, city) values ('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "')", con);
cmd.ExecuteNonQuery();
con.Close();
TextBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
}
}
When I am trying to insert the data, this error appears:

Table
is a SQL keyword, you should be able to use
[Table]
to distinguish your Table name from the keyword.
So try using
SqlCommand cmd = new SqlCommand("insert into [Table] (fname, lname, city) values ('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "')", con);

It's possible your textbox input contains a value that is escaping your string. The method you're using is open to sql injection attacks.
For example:
If textbox1.txt contains a ' character, it would break the query, because it would eacape the value.
You'd likely be able to see this if you look at the command text property of the SqlCommand object. I'd highly recommend you take a look at that property, and do some googling about sql injection. If your input on any of those boxes were " '; drop database; --", your whole database would be deleted.
This is likely an issue of your input not being sanitized or passed to sql correctly.

Related

Display ID and Value in DropDown using ASP.NET

There is a requirement of displaying both PackageID, and PackageName in a dropdown, so that customer can select the package for recharge.
As per the current code, PackageName is visbile using DataTextFiled property , which has been set in markup.
Please help to display both PackageID, and Package Name, and go through below codes-
DataBase-
CREATE TABLE [dbo].[PackageMaster](
[PackageID] [int] IDENTITY(1,1) NOT NULL,
[PackageName] [varchar](50) NULL
) ON
[PRIMARY]
Create Proc UspGetPackage
As
Begin
Select PackageID,PackageName from PackageMaster
End
--------------------------------------------------Design-------------------------------
<%# Page Language="C#" AutoEventWireup="true" CodeFile="PackageRequest.aspx.cs" Inherits="PackageRequest" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td><b>Select Package:</b></td>&nbsp
<td>
<asp:DropDownList ID="DDLPackage" runat="server" DataTextField="PackageName" DataValueField="PackageID"></asp:DropDownList>
</td>
</tr>
<tr>
<td><b>Select Sequence:</b></td>&nbsp
<td>
<asp:DropDownList ID="DDLPakcageSequence" runat="server" DataTextField="SequenceValue" DataValueField="SequenceID"></asp:DropDownList>
</td>
</tr>
<tr>
<td><asp:Button ID="btnSubmit" Text="Submit" runat="server" OnClick="btnSubmit_Click" /></td>
</tr>
</table>
</div>
</form>
</body>
</html>
----------------------CodeBehind---------------
private DataSet GetData(string SPName, SqlParameter SPParameter)
{
string CS = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
SqlConnection con = new SqlConnection(CS);
SqlDataAdapter da = new SqlDataAdapter(SPName, con);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
if (SPParameter != null)
{
da.SelectCommand.Parameters.Add(SPParameter);
}
DataSet DS = new DataSet();
da.Fill(DS);
return DS;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DDLPackage.DataSource = GetData("UspGetPackage",null);
DDLPackage.DataBind();
ListItem lstPkg = new ListItem("--Select Package--","-1");
DDLPackage.Items.Insert(0,lstPkg);
//DDLPakcageSequence.DataSource = GetData("UspGetPkgSequence",null);
//DDLPakcageSequence.DataBind();
//ListItem pkgsequence = new ListItem("--Select Sequence--", "-1");
//DDLPakcageSequence.Items.Insert(0, pkgsequence);
}
}
Concat two columns in stored procedure.
Select CONCAT(PackageID,' ', PackageName ) AS PackageID_PackageName, PackageID,PackageName from PackageMaster
In .aspx change DataTextField="PackageName" to DataTextField="PackageID_PackageName"
<asp:DropDownList ID="DDLPackage" runat="server" DataTextField="PackageID_PackageName" DataValueField="PackageID"></asp:DropDownList>

i am trying to run a asp.net method with an html submit button but method would not run?

I want the method submit_click to be activated when the submit button on the HTML part is pressed
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" Debug="true" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server" method="post" onsubmit="Submit_Click">
mail<br />
<asp:TextBox ID="mail" runat="server" Style="margin-left: 0px">mail</asp:TextBox>
<br />
name<br />
<asp:TextBox ID="name" runat="server" Width="117px">name</asp:TextBox>
<br />
last
<br />
<asp:TextBox ID="last" runat="server">name</asp:TextBox>
<p>
pass
</p>
<p>
<asp:TextBox ID="password" runat="server">password</asp:TextBox>
</p>
id <p>
<asp:TextBox ID="id1" runat="server">id</asp:TextBox>
</p>
<input id="Submit" type="submit" value="submit" onserverclick="Submit_Click()" />
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OleDb;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Submit_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0; Data source = " + Server.MapPath("") + "\\Database.accdb");
conn.Open();
string com = "INSERT into myusers (myid,myname,mymail,mypass,mylast) VALUES ('" + id1.Text + "," +name.Text + "," + mail.Text + "," +password.Text + "," + last.Text + "')";
OleDbCommand comm = new OleDbCommand(com, conn);
comm.ExecuteNonQuery();
conn.Close();
}
}
Actually why you're doing this , that i don't know because Asp Button will also converted like below on browser side, Still if you want to use it put runat="server", try below code.
<input id="Submit" runat="server" type="submit" value="submit" onserverclick="Submit_ServerClick" />
You are missing 'runat="server"'. Include it in the submit control.

have to search a query on a database such as a name and spit out anything that is similar

Basically it reads the database file on site, I want to then search a name for instance and then it will pop up with all results which are like the searchName and then output that as a table on a web page, this should be triggered by pressing the button and having typed a letter at least I have been fiddling with this for hours can anyone give me some insight on what I'm doing wrong? I'm also using Odbc to create a DNS on my system, this is a small project just need some trouble finding help as the Odbc code works for adding a record and viewing all records but messes up on this page.
Cheers, Josh
<%# Page Language="C#"%>
<%# Import Namespace="System.Data.Odbc" %>
<%
OdbcConnection oConn = new OdbcConnection("DSN=sailors");
oConn.Open();
string str_sql = "select * from MonsterList where MonsterNames like searchName"; // this is an sql string '*' includes all fields from table
OdbcCommand oCmd = new OdbcCommand(str_sql, oConn);
OdbcDataReader oRs = oCmd.ExecuteReader();
%>
<!DOCTYPE html>
<script runat="server">
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Search Monster</title>
</head>
<body>
<form method="post" runat="server">
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
<strong>Search </strong>
</td>
<td>
<asp:TextBox ID="searchName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<asp:Button ID="btnSubmit" runat="server" Text="Search" />
</td>
</tr>
</table>
</form>
<table <link rel="displayrecordSS" href="displayrecordSS.css"/>
<%
while(oRs.Read())
{
string str_out = #"<tr valign=""top"">" +
"<td>" + oRs["MonsterNames"] + "</td>" +
"<td>" + oRs["Element"] + "</td>" +
"<td>" + oRs["Weakness"] + "</td>" +
"</tr>" +
#"<tr bgcolor=""#ff0000""><td height=""1"" colspan=""3""></td></tr>";
Response.Write(str_out);
}
%>
</body>
</html>
<%
oRs.Close();
oRs = null;
oCmd.Dispose();
oCmd = null;
oConn.Close();
oConn.Dispose();
oConn = null;
%>
Working Add Page
<%# Page Language="C#" %>
<%# Import Namespace="System.Data.Odbc" %>
<%
OdbcConnection oConn = new OdbcConnection("DSN=sailors");
oConn.Open();
if ((Request["MonsterNames"] != null) && (Request["Element"].ToString() != ""))
{
string str_sql = #"insert into MonsterList (MonsterNames,Element, Weakness) values " +
"('" + Request["MonsterNames"] + "'," +
"'" + Request["Element"] + "', '" + Request["Weakness"] + "')";
OdbcCommand oCmd = new OdbcCommand(str_sql, oConn);
oCmd.ExecuteNonQuery();
oCmd.Dispose();
oCmd = null;
Response.Write("<br><br><br>");
}
%>
<!DOCTYPE html>
<script runat="server">
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Add Monster</title>
</head>
<body>
<div class="topnav" id="myTopnav">
<link rel="stylesheet" href="stylesheet.css" />
Home
Monster List
Search A Monster
</div>
<!-- all FORM elements (input, checkbox etc) contains data to submit. start of FORM -->
<form method="post" runat="server">
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
<strong>Monster Name:</strong>
</td>
<td>
<asp:TextBox ID="MonsterNames" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<strong>It's Element:</strong>
</td>
<td>
<asp:TextBox ID="Element" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<tr>
<td>
<strong>Known Weaknesses (Seperate by '/'):</strong>
</td>
<td>
<asp:TextBox ID="Weakness" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<asp:Button ID="btnSubmit" runat="server" Text="Add Record" />
</td>
</tr>
</table>
</form>
</body>
</html>
<%
oConn.Close();
oConn.Dispose();
oConn = null;
%>
Working Display All Page
<%# Page Language="C#"%>
<%# Import Namespace="System.Data.Odbc" %>
<%
OdbcConnection oConn = new OdbcConnection("DSN=sailors");
oConn.Open();
string str_sql = "select * from MonsterList "; // this is an sql string '*' includes all fields from table
OdbcCommand oCmd = new OdbcCommand(str_sql, oConn);
OdbcDataReader oRs = oCmd.ExecuteReader();
%>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Monster List</title>
</head>
<body leftmargin="0" rightmargin="0" topmargin="0">
<div class="topnav" id="myTopnav">
<link rel="stylesheet" href="stylesheet.css" />
Home
Add Monster
Search A Monster
</div>
<table <link rel="displayrecordSS" href="displayrecordSS.css"/>
<%
while(oRs.Read())
{
string str_out = #"<tr valign=""top"">" +
"<td>" + oRs["MonsterNames"] + "</td>" +
"<td>" + oRs["Element"] + "</td>" +
"<td>" + oRs["Weakness"] + "</td>" +
"</tr>" +
#"<tr bgcolor=""#ff0000""><td height=""1"" colspan=""3""></td></tr>";
Response.Write(str_out);
}
%>
</table>
</body>
</html>
<%
oRs.Close();
oRs = null;
oCmd.Dispose();
oCmd = null;
oConn.Close();
oConn.Dispose();
oConn = null;
%>

How do I save text entered in a TinyEditor box to my database

I am new to asp.net. Currently working on a form that uses tinyeditor to allow a user to input data. My question is, how can I get that HTML encoded text and save it to the database (Its MSSQL) upon pressing a button?
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="AboutMeEdit.aspx.cs" Inherits="InteractiveCV.AdminForms.AboutMeEdit" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<style type="text/css">
.auto-style1 {
width: 100%;
}
.auto-style2 {
height: 23px;
}
</style>
<script src="../Scripts/tinyEditor/tiny.editor.packed.js"></script>
<link href="../Styles/tinyeditor.css" rel="stylesheet" />
</head>
<body>
<form id="form1" runat="server">
<div>
<table class="auto-style1">
<tr>
<td class="auto-style2">Edit Your About Me in the below Text Box</td>
</tr>
<tr>
<td>
<asp:TextBox ID="tinyeditor" TextMode="MultiLine" Width="400" Height="200" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</td>
</tr>
<tr>
<td>
<asp:RequiredFieldValidator ID="aboutmevalidate" runat="server" ControlToValidate="tinyeditor" ErrorMessage="About Me Left Empty">About Me Left Empty</asp:RequiredFieldValidator>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
<script type="text/javascript">
var editor = new TINY.editor.edit('editor', {
id: 'tinyeditor',
width: 584,
height: 175,`enter code here`
cssclass: 'tinyeditor',
controlclass: 'tinyeditor-control',
rowclass: 'tinyeditor-header',
dividerclass: 'tinyeditor-divider',
controls: ['bold', 'italic', 'underline', 'strikethrough', '|', 'subscript', 'superscript', '|',
'orderedlist', 'unorderedlist', '|', 'outdent', 'indent', '|', 'leftalign',
'centeralign', 'rightalign', 'blockjustify', '|', 'unformat', '|', 'undo', 'redo', 'n',
'font', 'size', 'style', '|', 'image', 'hr', 'link', 'unlink', '|', 'print'],
footer: true,
fonts: ['Verdana', 'Arial', 'Georgia', 'Trebuchet MS'],
xhtml: true,
cssfile: 'custom.css',
bodyid: 'editor',
footerclass: 'tinyeditor-footer',
toggle: { text: 'source', activetext: 'code', cssclass: 'toggle' },
resize: { cssclass: 'resize' }
});
</script>
I have the following Codebehind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
namespace InteractiveCV.AdminForms
{
public partial class AboutMeEdit : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RIADDConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("INSERT INTO about_me (about_me) VALUES (#about_me)", conn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#about_me",tinyeditor.Text);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
protected void tinyeditor_TextChanged(object sender, EventArgs e)
{
}
}
}
Try this for TinyEditor:
<textarea ID="tinyeditor" runat="server"></textarea >
And for your code behind, to get the text use tinyeditor.value()

Issue with : "save picture as" in IE for an image retrieved from database via an image handler

I have a webpage that contains an aspImage control
When I retrive an image from database via an image handler I can show that image in the aspImage control ! BUT . . . the problem is when I right click on the image and click "save picture as" I get this error message : The file type being saved or retrieved has been blocked !
I wonder if this is an IE issue or something is wrong with my code ?! any help ?!
Here is my image handler code :
<%# WebHandler Language="C#" Class="Handler" %>
using System;
using System.Configuration;
using System.Data.SqlClient;
using System.Web;
public class Handler : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString);
public void ProcessRequest(HttpContext context)
{
string TableName=context.Session["TableToQuery"].ToString();
string ID=context.Session["ID"].ToString();
SqlCommand comm = new SqlCommand("SELECT * FROM "+ TableName +" WHERE ID=" + ID, conn);
conn.Open();
SqlDataReader dr = comm.ExecuteReader();
dr.Read();
context.Response.BinaryWrite((byte[])dr["Image"]);
conn.Close();
}
public bool IsReusable
{
get
{
return false;
}
}
}
And here is the datalist in wich I show my image :
<asp:DataList ID="DL" runat="server" Width="100%" Height="100%" RepeatColumns="1"
RepeatDirection="Vertical">
<ItemTemplate>
<table style="height: 100%; width: 100%">
<tr style="width: 100%; height: 350px">
<td valign="middle">
<asp:Image ID="IMage" runat="server" ImageUrl='<%# "Handler.ashx?ID=" + Eval("ID") %>' />
</td>
</tr>
<tr style="width: 100%; height: 250px">
<td valign="top">
<asp:TextBox ID="txtDecoded" runat="server" TextMode="MultiLine" Width="316px"
Height="200px" Text='<%#Eval("DecodedString")%>'></asp:TextBox>
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
You are not sending any headers declaring the MIME type of the contents, just a context.Response.BinaryWrite
At the very least you should add something like this before the BinaryWrite
context.Response.ContentType = "image/jpeg";

Categories

Resources