ASP.NET : Passing a outside variable into a <asp:sqldatasource> tag ASP.NET 2.0 - sql

I'm designing some VB based ASP.NET 2.0, and I am trying to make more use of the various ASP tags that visual studio provides, rather than hand writing everything in the code-behind. I want to pass in an outside variable from the Session to identify who the user is for the query.
<asp:sqldatasource id="DataStores" runat="server" connectionstring="<%$ ConnectionStrings:MY_CONNECTION %>"
providername="<%$ ConnectionStrings:MY_CONNECTION.ProviderName %>"
selectcommand="SELECT THING1, THING2 FROM DATA_TABLE WHERE (THING2 IN (SELECT THING2 FROM RELATED_DATA_TABLE WHERE (USERNAME = #user)))"
onselecting="Data_Stores_Selecting">
<SelectParameters>
<asp:parameter name="user" defaultvalue ="" />
</SelectParameters>
</asp:sqldatasource>
And on my code behind I have:
Protected Sub Data_Stores_Selecting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceSelectingEventArgs) Handles Data_Stores.Selecting
e.Command.Parameters("user").Value = Session("userid")
End Sub
Oracle squaks at me with ORA-01036, illegal variable name. Am I declaring the variable wrong in the query?
I thought external variables share the same name with a # prefixed. from what I understand, this should be placing the value I want into the query when it executes the select.
EDIT: Okay, thanks for the advice so far, first error was corrected, I need to use : and not # for the variable declaration in the query. Now it generates an ORA-01745 invalid host/bind variable name.
EDIT AGAIN: Okay, looks like user was a reserved word. It works now! Thanks for other points of view on this one. I hadn't thought of that approach.

I believe Oracle uses the colon ":", not the at-symbol "#".
"user" is probably a reserved word. Change it to "userID", or something similar.

You may want to consider using a SessionParameter instead of just a Parameter and let the SqlDataSource extract the user id directly from the session without any intervention on your part. Also, the example on the page linked above seems to imply that you should use ? instead of #user for parameter replacement for an ODBC connection. I think the parameter replacement would be done by the SqlDataSource and not passed to Oracle, that is it would substitute the actual value of the user id in place of the parameter (properly quoted of course) before sending the query to the database.
<SelectParameters>
<SessionParameter Name="userID" SessionField="user" DefaultValue="" />
</SelectParameters>

Using ASP.NET's SessionParameter is definitely the way to go here - that's why we have it :)
Using ASP.NET parameters you can easily include in your queries values from static sources, session state, query string, control property values, form post data, cookies, and user profile.

<asp:sqldatasource id="DataStores" runat="server" connectionstring="<%$ ConnectionStrings:MY_CONNECTION %>"
providername="<%$ ConnectionStrings:MY_CONNECTION.ProviderName %>"
selectcommand="SELECT THING1, THING2 FROM DATA_TABLE WHERE (THING2 IN (SELECT THING2 FROM RELATED_DATA_TABLE WHERE (USERNAME = #user)))"
onselecting="NAME_OF_SUB_Selecting">
<SelectParameters>
<asp:parameter name="#user1" defaultvalue ="" />
</SelectParameters>
</asp:sqldatasource>
Protected Sub NAME_OF_SUB_Selecting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceSelectingEventArgs) Handles Data_Stores.Selecting
e.Command.Parameters("#user1").Value = Membership.GetUser.ProviderUserKey.ToString()
End Sub

Related

Inserting into a database with ASP.NET causes error

I am working with VS 2017 for the first time.
I am trying to insert some values into a database. I already made the connection (checked with select statement) with the database, but now I am stuck in the insert portion.
I have a SqlDataSource defined as:
<div>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString=" <%$ ConnectionStrings:Sphinxx_Conn %>"
ProviderName="<%$ ConnectionStrings:Sphinxx_Conn.ProviderName %>"
InsertCommand="INSERT INTO "DEMO" ("ID", "NAME") VALUES (:ID, :NAME)">
<InsertParameters>
<asp:Parameter Name="ID" Type="String" />
<asp:Parameter Name="NAME" Type="String" />
</InsertParameters>
</asp:SqlDataSource>
</div>
Now the following snippet:
SqlDataSource1.InsertParameters["ID"].DefaultValue = '1'
SqlDataSource1.InsertParameters["NAME"].DefaultValue = 'John'
Underlines the 'SqlDataSource1.InsertParameters' part and shows an error:
Property access must assign to the property or use its value.
What exactly am I doing wrong?
You are passing invalid data because you are using single quotes, use double quotes instead:
SqlDataSource1.InsertParameters["ID"].DefaultValue = "1";
SqlDataSource1.InsertParameters["NAME"].DefaultValue = "John";
On the side note, if you started working and getting to know web development with Visual Studio, i recommend you to look at MVC. Web Forms are old tech that is no longer supported.
There are 2 errors within your Code Snippet of assigning values.
You are setting a char value instead of string, replace single quoted 'values with double quotes ". Instead of '1' do this "1" same with John too.
You have not used ; to terminate your statement, so put semicolons in the end of your statements.

Using user.identity.Name in SQL statement

In my ASP.NET app, I have the following SQL which works:
<asp:SqlDataSource ID="ISESDatabase" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT [id], [Word], [Definition], [Example] FROM [gridData] WHERE [Strategy]='Vocabulary'">
However, I need to add a user id check to the Where clause, and am hoping to use user.identity.Name to perform the check. I have tried the following, but it doesn't work:
<asp:SqlDataSource ID="ISESDatabase" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT [id], [Word], [Definition], [Example] FROM [gridData] WHERE [userid]= /'" + user.identity.Name + "/' AND [Strategy]='Vocabulary'">
Here is the error:
Parser Error
Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.
Parser Error Message: The server tag is not well formed.
Source Error:
Line 46: <asp:SqlDataSource ID="ISESDatabase" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT [id], [Word], [Definition], [Example] FROM [gridData] WHERE [userid]=/'" + User.Identity.Name + "/' AND [Strategy]='Vocabulary'">
What am I doing wrong?
I think you need to rethink your approach. Rather than trying to 'hard-code' the 'user.Identity.Name' property in the asp:SqlDataSource element, try creating a parameter to hold this value:
1) Replace 'user.Identity.Name' in your SelectCommand with a token for the parameter, such as '#Name'.
2) Then define a SelectParameter element for the asp:SqlDataSource that has a Name property of 'Name'. Set the Type property of the parameter to whatever is the data type of 'user.Identity.Name'.
3) Then, you can define the value that you want to select programmatically in an event handler for the Selecting event of the SqlDataSource.
Here's an example that works. The following code snippet is from the aspx page:
<asp:GridView ID="myGridView" runat="server" DataSourceID="myDataSource" DataKeyNames="ID"></asp:GridView>
<asp:SqlDataSource ID="myDataSource" runat="server"
SelectCommand="SELECT * FROM [Users] WHERE [Name] = #Name"
ConnectionString='Data Source=(LocalDB)\v11.0;AttachDbFilename="c:\users\windowsLogin\documents\visual studio 2012\Projects\WebApplication1\WebApplication1\App_Data\Database1.mdf";Integrated Security=True'>
<SelectParameters>
<asp:Parameter Name="Name" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
Then, in the code-behind, you can define your parameter programmatically at run-time based on whatever criteria matter. (Here, I'm just assigning the value '2' to the #Name parameter; you could replace it with 'user.Identity.Name'.)
Private Sub myDataSource_Selecting(sender As Object, e As SqlDataSourceSelectingEventArgs) Handles myDataSource.Selecting
e.Command.Parameters("#Name").Value = 2
End Sub
I hope this is clear... If not, refer to the documentation on MSDN. Here are a couple of pages to get you started:
SqlDataSource.SelectCommand Property
SqlDataSourceSelectingEventArgs Class
and, more generally,
Using Parameters with Data Source Controls for Filtering
To escape special char in string is to use backslash '\' not forward slash '/'. Try this and see if it works:
<asp:SqlDataSource ID="ISESDatabase" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT [id], [Word], [Definition], [Example] FROM [gridData] WHERE [userid]= \'" + user.identity.Name + "\' AND [Strategy]='Vocabulary'">
UPDATE: The answer is not this simple, as tested by sroonet. The actual answer is to use parameterized query in the SelectCommand. For details about using parameterized query in SelectCommand, please refer to the following webpage:
https://msdn.microsoft.com/en-us/library/z72eefad.aspx

sql data source used to work in visual studio 2005 but not now in 2010

I have a sql data source declared on an aspx page which worked fine in Visual Studio 2005, but since migrating to Visual Studio 2010 the DefaultValue parameter is not evaluating the specified function and or the value passed in from a property in the code behind. When checked in SQL Query Analyser the code passed to the database is just using the DafaultValue as a literal string. How can I rectify this?
<!--sql data source-->
<asp:SqlDataSource id="sdsltblCNS_SECOND_REF" runat="server" ConnectionString="<%$ ConnectionStrings:SCRConnectionString %>"
SelectCommand="Sel_CNS_SECOND_REFByCASite" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:Parameter DefaultValue='<%= Common.GetSiteName(Me.SelectedSite) %>' Name="CASite" ConvertEmptyStringToNull="true" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
' SelectedSite property
Public ReadOnly Property SelectedSite As Site
Get
If ViewState("SelectedSite") Is Nothing Then
ViewState("SelectedSite") = Common.GetSiteByCareID(CareID)
End If
Return ViewState("SelectedSite")
End Get
End Property
-- query analyser
exec Sel_CNS_SECOND_REFByCASite #CASite=N'<%= Common.GetSiteName(Me.SelectedSite) %>'
Maybe I'm stating the obvious and missing something deeper (it's been a long day) but shouldn't you be using a quotation mark versus a single tick, as in:
<asp:Parameter DefaultValue="<%= Common.GetSiteName(Me.SelectedSite) %>" Name="CASite" ConvertEmptyStringToNull="true" Type="String" />

Public Property as ObjectDataSource Select Parameter

I have an ODS, which is bound to an ADO.NET datatable. There is one select parameter. I would like to use a public property which I have declared in my code-behind as the select parameter, something like:
<SelectParameters>
<asp:ControlParameter ControlID='<%# EInfoProperty %>' Name="quote_header_id"
PropertyName="headerId" Type="Int32" />
</SelectParameters>
The above syntax doesn't work, and I've been unable to find anything here, on MSDN or on Google that might help here. Is there a way to do this, or am I stuck sticking the value in the Session, or something?
From everything I could find, this is not currently possible. For my purposes, I ended up putting the value in question in the session and using a SessionParameter.

GridView Updating on ItemCommand

i put all my custom "update" code in the RowCommand event, it works fine, but i still get an error from my Data Source
System.NotSupportedException: Updating
is not supported by ObjectDataSource
'GetSources' unless the UpdateMethod
is specified.
how can i get rid of that error , yes still use my custom update code on the rowcommand?
Well, I think the way the ObjectDataSource is intended to be used is you specify the name of the method in your custom business object, and it will use reflection to call that method.
So, your page and object might look something like this:
<asp:objectdatasource
id="ObjectDataSource2"
runat="server"
updatemethod="MyUpdateMethod"
typename="MyBusinessObject">
<updateparameters>
<asp:controlparameter name="anID" controlid="DropDownList1" propertyname="SelectedValue" />
</updateparameters>
</asp:objectdatasource>
Public Class MyBusinessObject
Public Shared Sub MyUpdateMethod(anID As String)
'data access code
End Sub
End Class
This pattern of putting control together can be quite productive, but you'll probably feel too restricted after a while.