ASP.NET / VB.NET : Generate Insert Command - asp.net

I have all of my form variables in my codebehind, they were all retrieved using "Request.Form".
As Far as I Know..If I use the SQLDataSource to do this I have to use ASP.NET Controlls(which I do not want).
INSERT INTO Orders(FirstName, LastName, Email, PhoneNumber, Address, City, State, ZipCode, PaymentMethod, PromoCode, OrderStatus, Tracking, PPEmail, SubmissionDate) VALUES (#FirstName, #LastName, #Email, #Phone, #Address, #City, #State, 11111, #PaymentMethod', '0', 'New Order - Pending', '0', #PPEMAIL, #Date)
CodeBehind
Dim fPrice As String = CType(Session.Item("Qprice"), String)
Dim DeviceMake As String = CType(Session.Item("Make"), String)
Dim PaymentMethod As String = Request.Form("Payment Type")
Dim DeviceModel As String = CType(Session.Item("Model"), String)
Dim DeviceCondition As String = CType(Session.Item("Condition"), String)
Dim SubmissionDate As String = Date.Now.ToString
Dim FirstName = Request.Form("First")
Dim LastName = Request.Form("Last")
Dim City = Request.Form("City")
Dim Phone = Request.Form("Phone")
Dim Address = Request.Form("Address")
Dim State = Request.Form("State")
Dim Zip = Request.Form("Zip")
Dim Email = Request.Form("EMail")
Is there a way I can attatch my variables to the insert statment generated by the SQLDatasource, without having to manually code the parameters?

You could use FormParameter. This doesn't require any ASP.NET control so far I'm aware.
<asp:sqldatasource
id="SqlDataSource1"
runat="server"
connectionstring="<%$ ConnectionStrings:MyNorthwind %>"
selectcommand="SELECT CompanyName,ShipperID FROM Shippers"
insertcommand="INSERT INTO Shippers (CompanyName,Phone) VALUES (#CoName,#Phone)">
<insertparameters>
<asp:formparameter name="CoName" formfield="CompanyNameBox" />
<asp:formparameter name="Phone" formfield="PhoneBox" />
</insertparameters>
</asp:sqldatasource>
Pay special attention to Microsoft warning in relation to this mechanism
The FormParameter does not validate the value passed by the form element in any way; it uses the raw value. In most cases you can validate the value of the FormParameter before it is used by a data source control by handling an event, such as the Selecting, Updating, Inserting, or Deleting event exposed by the data source control you are using. If the value of the parameter does not pass your validation tests, you can cancel the data operation by setting the Cancel property of the associated CancelEventArgs class to true.

Its probably better that you forcibly attach the parameters. As you are getting your values from Form and Session (ick), parameterizing the SQL will give you some measure of protection.
You may want to explore code generation (A-la T4), this way you can point the codegen at a proc/table and it will generate the vb code to call it, attach the params and execute the statement.

Related

Convert ASP.NET textbox control .text contents to Date/Time format

I am trying to insert into a database - various details about an event. The asp.net textbox is using the Calendar Extender (so a little calendar pops up and fills the textbox with a correctly formatted date). The EventDate field in my Access database is of the type Date/Time. I need to convert the text/string to date/time format
I have tried this so far:
VB:
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim oleDbConn As New OleDb.OleDbConnection(ConfigurationManager.ConnectionStrings("BookMeetConnString").ConnectionString)
Dim SqlString As String = "Insert into Events(EventTitle,EventDescription,EventDate,EventCategory) Values
(#f1,#f2,#f3,#f4)"
Dim cmd As OleDbCommand = New OleDbCommand(SqlString, oleDbConn)
Dim strDate As String = tb_eventdate.Text
Dim dtfi As New System.Globalization.DateTimeFormatInfo
dtfi.ShortDatePattern = "dd/MM/yyyy"
dtfi.DateSeparator = "/"
Dim objDate As DateTime = Convert.ToDateTime(strDate, dtfi)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("#f1", tb_eventtitle.Text)
cmd.Parameters.AddWithValue("#f2", tb_eventdescription.Text)
cmd.Parameters.AddWithValue("#f3", tb_eventdate.Text)
cmd.Parameters.AddWithValue("#f4", dd_eventcategory.Text)
oleDbConn.Open()
cmd.ExecuteNonQuery()
System.Threading.Thread.Sleep("2000")
Response.Redirect("~/calendar.aspx")
End Sub
Here is my clientside code just for reference:
<h1>Add An Event!<ajaxToolkit:ToolkitScriptManager
ID="ToolkitScriptManager1"
runat="server">
</ajaxToolkit:ToolkitScriptManager>
</h1>
<p>Title of Event:
<asp:TextBox ID="tb_eventtitle" runat="server"></asp:TextBox>
</p>
<p>Event Description:
<asp:TextBox ID="tb_eventdescription" runat="server"></asp:TextBox>
</p>
<p>Event Date:
<asp:TextBox ID="tb_eventdate" runat="server"></asp:TextBox>
<ajaxToolkit:CalendarExtender ID="tb_eventdate_CalendarExtender" runat="server"
TargetControlID="tb_eventdate">
</ajaxToolkit:CalendarExtender>
</p>
<p>Event Category:
<asp:DropDownList ID="dd_eventcategory" runat="server"
DataSourceID="SqlDataSource1" DataTextField="CategoryTitle"
DataValueField="CategoryTitle">
</asp:DropDownList>
</p>
<p>
<asp:Button ID="Button1" runat="server" Text="Submit" />
</p>
When I try to fill out the form, I receive this error:
My Two questions are:
What is wrong with the code above, and how do I successfully use the DateTimeFormatInfo class to convert String to Date/Time?
On a side note, the Calendar Extender inputs the date into the textbox in American Time format (MM/DD/YYYY), how do I change this to British (DD/MM/YYYY) format (I couldn't see an obvious property in the properties dialog to do this?)
Thanks in advance for your answers!
Adam
EDIT: Updated code below:
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim oleDbConn As New OleDb.OleDbConnection(ConfigurationManager.ConnectionStrings("BookMeetConnString").ConnectionString)
Dim SqlString As String = "Insert into Events(EventTitle,EventDescription,EventDate,EventCategory) Values
(#f1,#f2,#f3,#f4)"
Dim cmd As OleDbCommand = New OleDbCommand(SqlString, oleDbConn)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("#f1", tb_eventtitle.Text)
cmd.Parameters.AddWithValue("#f2", tb_eventdescription.Text)
cmd.Parameters.AddWithValue("#f3", DateTime.ParseExact(tb_eventdate.Text, "dd/MM/yyyy",
CultureInfo.InvariantCulture))
cmd.Parameters.AddWithValue("#f4", dd_eventcategory.Text)
oleDbConn.Open()
cmd.ExecuteNonQuery()
System.Threading.Thread.Sleep("2000")
Response.Redirect("~/calendar.aspx")
End Sub
I'd recommend you use DateTime.ParseExact static method, especially this oveload:
DateTime.ParseExact(textBox.Text, "dd/MM/yyyy",CultureInfo.InvariantCulture)
This will parse the text you have by the concrete format you specify ("dd/MM/yyyy" currently, case is important since mm is minutes as opposed to MM being months). Use of CultureInfo.InvariantCulture guarantees that date separators will be retrieved from the format string (the second parameter). I have noticed that if current culture is used, it overrides some aspects of the format string you pass to ParseExact.
A note on CultureInfo
Invariant culture is good also for the reason that your local dev environment may have different regional information setup than the deployment environment. Usually, .NET uses the current culture in all .ToString calls and implicit formatting or parsing. When forcing a format and culture invariance explicitly, you are less prone to problems you cannot reproduce locally but exist on the production application.
A note on date/time formats
With exact parsing, the datetime format is expected to strictly match the format of the input. You should then take into consideration the following examples:
dd matches two-digit days only. So "dd/MM/yyyy" it will match "01/01/2013", but will fail for "1/1/2013" because it expects the exact number of digits for the day part. If you do not want leading zeros use: d/M/yyyy instead. Single letter means one digit for days less than 10 and two digits for the others.
MM matches two-digit month, so all that applies to dd vs. d is the same for months.
yyyy expects the year to be in 4 digits. If you use two-digit year, use yy instead.
A note on some ADO.NET providers
As it turns out to be the case with MS Access, the correctly parsed date-time object is not sufficient to make the query work. Currently, the following code
cmd.Parameters.AddWithValue(...)
is used to add parameters to the query. However, this approach omits passing information to the ADO.NET db provider that tells what database type to use for the parameter. I have read on some forums that MS Access/OleDb is not capable to resolve the correct type in all cases. Therefore I recommend the following approach:
Dim prm as OleDbParameter = _
New OleDbParameter("#dateTimeParameterName", OleDbType.DateTime)
prm.Value = value 'value is an instance of `System.DateTime` parsed
'from the input
cmd.Parameters.Add(prm)
The above code allows to specify the parameter database type explicitly, so the OleDb driver is now capable of correctly passing the DateTime object to the MS Access database.
I used below short code:
//myDateValue is System.DateTime object.
OleDbCommand commandObject = new OleDbCommand();
...
commandObject.Parameters.Add(new OleDbParameter("#ADDED_DATE_PARAM", OleDbType.Date).Value = myDateValue);

Passing a Session.Item to a MySQL query

I have a aspx web page that has a session variable:
Dim UserName As String = CType(Session.Item("UserName"), String)
I am attempting to include this variable in the MySQL query of a SqldataSource for a Databound GridView control:
Dim Sql As String = "SELECT DeviceDescription, DeviceType, DeviceID
FROM validate WHERE ClientID='" & UserName & "'"
However, this does not work.
How do you pass/include this session variable in the DataSource of the GridView?

Adding duplicate rows of data to my access database

Hey there Im having difficulties adding a single row of data to my database when I submit my form it insert two rows of data to my mdb database any suggestions samples or help will work ill really appreciate it Thanks
Protected Sub Button3_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button3.Click
Dim conCoaxis As OleDbConnection
Dim strInsert As String
Dim cmdInsert As OleDbCommand
conCoaxis = New OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0;Data Source=C:\site\App_Data\sabersolutions.mdb")
strInsert = "INSERT INTO register (Name, Email, Newsletter) Values (?, ?, ?)"
cmdInsert = New OleDbCommand(strInsert, conCoaxis)
cmdInsert.Parameters.Add("#Name", OleDbType.VarWChar, 255).Value = txtName.Text
cmdInsert.Parameters.Add("#Email", OleDbType.VarWChar, 255).Value = txtEmail.Text
cmdInsert.Parameters.Add("#Newsletter", OleDbType.Boolean, 1).Value = ckNews.Checked
Try
conCoaxis.Open()
cmdInsert.ExecuteNonQuery()
conCoaxis.Close()
Response.Write("Updated Successfully!<p> </p><p> </p><p> </p>")
Catch
conCoaxis.Close()
End Try
Your code looks fine. It looks to me more like you have the sub-routine Button3_Click assigned as the handler more than once. For example in the aspx page you have something like
<asp:Button runat="server" ID="Button3" Text="Submit" OnClick="Button3_Click" />
See the OnClick attribute? that wires the click event to call Button3_Click
Then somewhere else, possibly in Page_Load in the .vb code-behind, you also have:
AddHandler Button3.Click, AddressOf Me.Button3_Click
So ONE click event will end up calling the same function twice. Get rid of the AddHandler code you don't need to manually wire-up click handlers, it's done for you.
If that's not your problem you may of course be clicking your button twice, this is a well known issue with HTML forms. You can Google many solutions. My preferred solution is to always do a 'SELECT' first to check if the record already exists, or wrap your insert command in a 'IF NOT EXISTS' (I think this works for MS Access, I know it dows for MS Sql Server)
strInsert = "IF NOT EXISTS (SELECT 1 FROM register WHERE Name = #Name AND Email = #Email AND Newsletter = #Newsletter) BEGIN INSERT INTO register (Name, Email, Newsletter) Values ( #Name, #Email, #Newsletter) END"
Another option is:
strInsert = "INSERT INTO register (Name, Email, Newsletter) SELECT TOP 1 #Name, #Email, #Newsletter FROM register WHERE NOT EXISTS (SELECT 1 FROM register WHERE Name = #Name AND Email = #Email AND Newsletter = #Newsletter)"
This latter statement only works if 'register' has at least one record in it, MS Access Jet database requires a table name in the statement, see here for more info. Seriously though, drop Access and use a proper database like SQL Server, then you can use the first statement directly or via a stored procedure a much more professional solution.

error in nvarchar to date, date not supplied, either problem in onclick event or stored procedure or in gridview

For your information, I am using Visual Studio Professional 2010
Can someone please help me out, I think the #dateFound parameter is not supplied with a value on click event.
I have a gridview populated from stored procedure as given below.
<asp:SqlDataSource id="Sql20"
ConnectionString='<%$ ConnectionStrings:connectionString %>'
SelectCommand="dbo.StoredProcedure2"
Runat="server" SelectCommandType="StoredProcedure">
</asp:SqlDataSource>
The storedProcedure2 is as follow which is suppose to show all the data in gridview if #dateFound IS NULL, by default as below
ALTER PROCEDURE dbo.StoredProcedure2
(
#dateFound DATE
)
AS
/* SET NOCOUNT ON */
IF #dateFound IS NULL
BEGIN
SELECT
lc_orders_tb.lc_orderID,
lc_orders_tb.lc_orderSubTotal,
lc_orders_tb.lc_orderTotal,
lc_orders_tb.LRNo,
lc_orders_tb.LRDate,
lc_orders_tb.lc_orderPlacedDate,
lc_orders_tb.LInvoiceLoc,
lc_orderStatus_tb.lc_orderStatusDescrip,
lc_orderStatus_tb.lc_delType,
lc_tb.lc_compName,
lc_tb.lc_addCity,
(SELECT SUM(lc_orderQuantity)
FROM lc_orderQuantity_tb
WHERE
lc_orders_tb.lc_orderID=lc_orderQuantity_tb.lc_OrderID) as lc_orderQuantity
FROM lc_orders_tb
INNER JOIN
lc_tb ON lc_orders_tb.lc_id = lc_tb.lc_id
INNER JOIN
lc_orderStatus_tb ON lc_orders_tb.lc_orderID = lc_orderStatus_tb.lc_orderID
ORDER BY lc_orders_tb.lc_orderPlacedDate DESC
END
ELSE
BEGIN
SELECT
lc_orders_tb.lc_orderID,
lc_orders_tb.lc_orderSubTotal,
lc_orders_tb.lc_orderTotal,
lc_orders_tb.LRNo,
lc_orders_tb.LRDate,
lc_orders_tb.lc_orderPlacedDate,
lc_orders_tb.LInvoiceLoc,
lc_orderStatus_tb.lc_orderStatusDescrip,
lc_orderStatus_tb.lc_delType,
lc_tb.lc_compName,
lc_tb.lc_addCity,
(SELECT SUM(lc_orderQuantity)
FROM lc_orderQuantity_tb
WHERE
lc_orders_tb.lc_orderID = lc_orderQuantity_tb.lc_OrderID) as lc_orderQuantity
FROM lc_orders_tb
INNER JOIN
lc_tb ON lc_orders_tb.lc_id = lc_tb.lc_id
INNER JOIN
lc_orderStatus_tb ON lc_orders_tb.lc_orderID = lc_orderStatus_tb.lc_orderID
WHERE
convert(varchar(10), lc_orders_tb.lc_orderPlacedDate, 103) = #dateFound
ORDER BY lc_orders_tb.lc_orderPlacedDate DESC
END
RETURN
#dateFound will be supplied when clicked on a button click but by default, I mean, when page loads it is not supplied and therefore it should execute the first if statement but it different errors like #dateFound not supplied or error on converting nvarchar to date. The ELSE statement of the SP should get executed if #dateFound supplied from the textbox after clicking on the button. But I cant seem to work out. Please have a look at the click event of the button which is supplying the #dateFound
Protected Sub CustomGV3_onClick(ByVal sender As Object, ByVal e As EventArgs)
Dim connectionString As String =
WebConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim con As New SqlConnection(connectionString)
Dim cmd As New SqlCommand("dbo.StoredProcedure2", con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue
("#dateFound", Format(txtBoxDateFrom.Text, "dd/MM/yyyy"))
Using con
con.Open()
cmd.ExecuteReader()
con.Close()
End Using
GridView3.DataBind()
End Sub
Can someone please help me out. Does it seem like I have a totally wrong approach ? Can someone please correct me.
awaiting your kind help plz..
Thanking You
Try changing your stored procedure to use a default value for the #dateFound parameter:
ALTER PROCEDURE dbo.StoredProcedure2
(
#dateFound DATE = NULL
)
AS
I finally got the answer from other forum, it worked by simply changing following in the SP
(
#dateFound DATE = '01/01/1900'
)
The above date is set as default as it will never be going to be in the database against which I will be checking by IF STATEMENT in SP. And in the aspx page to as below.
<SelectParameters>
<asp:ControlParameter ControlID="txtBoxDateFrom"
Name="dateFound" PropertyName="Text"
DbType="Date" DefaultValue="01/01/1900" />
Thanks to all contributor who tried to help me out here..

ASP.net: Sqldatasource and Session variable

<asp:HiddenField ID="hfDualInitials" runat="server" Visible="false" OnInit="hfDualInitials_OnInit" />
<asp:SqlDataSource ID="sdsStoreNo" runat="server" ConnectionString="<%$ ConnectionStrings:ConnStr %>"
SelectCommand="select * from AccountCancellation_Process
where store_num in (select distinct storeno from franchisedata where initials in (#DualInitials))
order by CustomerName ASC" >
<SelectParameters>
<asp:ControlParameter ControlID="hfDualInitials" DbType="String" Name="DualInitials" />
</SelectParameters>
</asp:SqlDataSource>
I have a Sqldatasource with the above select command and the below code to set the hiddenfield value
Protected Sub hfDualInitials_OnInit(ByVal sender As Object, ByVal e As EventArgs)
Dim _DualInitials As String = "('P2','7T')"
Session.Add("DualInitials", _DualInitials)
Me.hfDualInitials.Value = Session("DualInitials")
End Sub
I'm mocking the Session with ('P2','7T') that is going to pass into the above sql command.
when i run the query:
select * from AccountCancellation_Process where store_num in (select distinct storeno from franchisedata where initials in ('P2','7T'))
it return some data but in my Sqldatasource select command. It return nothing. my guess is because of the where initials in (#DualInitials) the ( ) that is already in the hiddenfield but if i remove the ( ) and just have #DualInitials. I will get "Incorrect syntax near '#DualInitials'."
Does anyone know any workaround or where i get it wrong?
Check out answers to the ADO.NET TableAdapter parameters question.
You have a query with a string parameter, not an array parameter. So, when you pass "('P2','7T')" you think that the final query is
WHERE initials IN ('P2', '7T')
In reality it is
WHERE initials IN ('(''P2'', ''7T'')')
If it is only going to be two initials then just rewrite using the OR statement. Otherwise I don't know good solution outside of those mentioned in the other thread.
You can't paramterize an IN statement in SQL like that. You'll have to use string concatenation of the SQL instead (bad) or some other technique like parsing a delimited string.
Without running the sample, I can't be sure, but what about
WHERE initials IN (<%=Eval(#DualInitials)%>)

Resources