How to set SelectCommand to change 'WHERE' to logged in user - sql

I've been working on webforms and per user data on ASP.NET where if a user logs in, they get their data.
I have a table where it takes the sqldatasource from an asp markup code:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:DefaultConnection %>"
ProviderName="<%$ ConnectionStrings:DefaultConnection.ProviderName %>"
SelectCommand="SELECT [first_name], [last_name], [weight_data] FROM [userData]
WHERE [email]='test#test.com';">
</asp:SqlDataSource>
I can get the currently logged in email string through <%: Context.User.Identity.GetUserName() %>
How would I put that into the WHERE email statement so I can take currently logged in user's email and replace it with 'test#test.com' to match it on the SQL table to get the other data?
Thanks a lot!

Different ways like:
You can use the built in OnSelecting parameter of asp:SqlDataSource
<asp:SqlDataSource ID="SqldsExample" runat="server"
SelectCommand="SELECT [first_name], [last_name], [weight_data] FROM [userData]
WHERE [email]=#UserEmail"
OnSelecting="SqldsExample_Selecting">
<SelectParameters>
<asp:Parameter Name="UserEmail" Type="String"/>
</SelectParameters>
In code-behind
protected void SqldsExample_Selecting(object sender, SqlDataSourceCommandEventArgs e)
{
e.Command.Parameters["UserEmail"].Value = Context.User.Identity.GetUserName();
}
Another way:
SqlDataSource1.SelectParameters.Add("#UserEmail", Context.User.Identity.GetUserName());
Hope this helps!

Related

Callback error: Specific cast is not valid

I'm using a devexpress editform on my visual basic project. I ask for user input on a ASPxGridView, one of the values is called, Start Date which is declare on the grid as:
<dx:GridViewDataDateColumn Caption="Start Date" FieldName="StartDate" HeaderStyle-Wrap="true" UnboundType="String" EditFormSettings-VisibleIndex="1" >
<PropertiesDateEdit DisplayFormatString="D" EditFormatString="D" ValidationSettings-RequiredField-IsRequired ="true"></PropertiesDateEdit>
</dx:GridViewDataDateColumn>
And the datasource looks like this:
<asp:SqlDataSource ID="SqlDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:SpEdPortalConnectionString %>"
SelectCommand="ProcedureName" SelectCommandType="StoredProcedure"
UpdateCommand="ProcedureName" UpdateCommandType="StoredProcedure"
InsertCommand="ProcedureName" InsertCommandType="StoredProcedure">
<SelectParameters>
***
</SelectParameters>
<UpdateParameters>
***
</UpdateParameters>
<InsertParameters>
***
<asp:Parameter Name="StartDate" Type="String" />
***
</InsertParameters>
</asp:SqlDataSource>
Problem: Even if I actually select a datevalue for the StartDate the value inserted on the DB is null.
Note:The callback error only shows on the deployed server not on local environment.But on local it inserts null so seems like the problem is there too but is not throwing an exeption.
I could not find the cause but the problem was solve by adding an EditTemplate tag and manually binding the value as follows:
<dx:GridViewDataDateColumn Caption="Start Date" FieldName="StartDate" HeaderStyle-Wrap="true" UnboundType="String" EditFormSettings-VisibleIndex="1" >
<PropertiesDateEdit DisplayFormatString="D" EditFormatString="D" ValidationSettings-RequiredField-IsRequired ="true"></PropertiesDateEdit>
<EditItemTemplate>
<dx:ASPxDateEdit ID="dteSD" runat="server" ClientInstanceName="dteSD"
Date='<%# Bind("StartDate") %>'>
</dx:ASPxDateEdit>
</EditItemTemplate>
</dx:GridViewDataDateColumn>
If the format changes you can just add Theme property inside the dx:ASPxDateEdit tag

Display image from database asp.net vb

I have database
Id int
img varbinary(MAX) --> image
descr nvarchar(50)
and now I want to display image and description. I use the following code
<div>
<asp:GridView
ID="GridView1"
runat="server"
AutoGenerateColumns="False"
DataKeyNames="Id"
DataSourceID="SqlDataSourceH"
CssClass="myGridView"
RowStyle-CssClass="rows"
ShowHeader="false">
<Columns>
<asp:ImageField
DataImageUrlField = "Id"
DataImageUrlFormatString = "Hardware.aspx?Id={0}"
ControlStyle-Width = "100"
ControlStyle-Height = "100"></asp:ImageField>
<asp:BoundField DataField="descr"></asp:BoundField>
</Columns>
</asp:GridView>
<asp:SqlDataSource
runat="server"
ID="SqlDataSourceH"
ConnectionString='<%$ ConnectionStrings:ConnectionString %>'
SelectCommand="SELECT [Id], [img], [descr] FROM [Hardware]">
</asp:SqlDataSource>
</div>
but image is not displayed
What should I do to display the picture?
Check /Images/theimage.jpg really exists then you need to go into the database and put the full path in the column img.
Also if it is in the folder /Images/ then you need "../Images/theimage.jpg" to go back to the root folder. Check the value of the url copy it to clipboard and dump it in the address bar and see if it comes up, so http://localhost/(dump url here) if it doesn't come up then you need to check the path and update the url value in database.

How to pass the querystring parameter into FormControl in vb.net

I am passing a value from one form to the other. The second form in inserting the data field into the table. How do I pass the ID(strPID) passed from the first form into the form control PatronIDTextBox of the second form?
VB.Code: on Page load -- strPID = Request.QueryString("value1")
Form control:
<InsertItemTemplate>
PatronID:
<asp:TextBox ID="PatronIDTextBox" runat="server" Text='<%# Bind("PatronID") %>' />
Thanks
Ok, Now I am trying to say it this way in object datasource so I can send it into insert statement without being displayed on the screen.
<Insert Parameters>
<asp:QueryStringParameter Name="PatronID" Type="int32" QueryStringField="value1" />
<asp:QueryStringParameter Name="PatronName" Type="String" QueryStringField="value2" />
</InsertParameter>
InsertCommand="INSERT INTO [tblIncident] ([PatronID], [PatronName]) values (#PatronID, #PatronName)
Have you tried directly putting the value into the textbox? Like this:
<asp:TextBox ID="PatronIDTextBox" runat="server" Text='<%= Request.QueryString("Value1") %>' />
Just be careful, because this approach could allow a XSS attack. You might want to read-up on those.
I deleted the text box for both id and name and instead I modified the objectdatasource Insert statement as follows. The value of value1 and value2 is captured on page load event.
<InsertParameters>
<asp:QueryStringParameter Name="PatronID" Type="Int32" QueryStringField="value1" />
<asp:QueryStringParameter Name="PatronName" Type="String" QueryStringField="value2"/>
</InsertParameters>

how to retrieve binary image from database in vb.net and insert the image in grid view

How to retrieve a binary image from a database using vb.net and insert the image into a GridView.
This is my DB
image (id as integer , img as varbinary(max))
While you clarify the type of gridview you are referring to, here's how to insert the data in the database:
Using c As New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
c.Open()
Dim command = New SqlCommand("INSERT INTO yourtable(image) values (#image)", c)
' this is specific to the FileUploadControl but the idea is to get the
'image in a byte array; however you do it, it doesn't matter
Dim buffer(FileUpload1.PostedFile.ContentLength) As Byte
FileUpload1.PostedFile.InputStream.Read(buffer, 0, buffer.Length)
command.Parameters.AddWithValue("#image", buffer)
command.ExecuteNonQuery()
End Using
And assuming you are talking about an ASP .NET app, you can bind the data to the gridview as follows:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="id" DataSourceID="SqlDataSource1">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<!--Trick to encode the bytes as a BASE64 string-->
<img width="100px" height="100px" src='data:image/png;base64,<%#System.Convert.ToBase64String(Eval("image"))%>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="Data Source=Your_ConnectionString_GoesHere"
ProviderName="System.Data.SqlClient"
SelectCommand="SELECT [id], [image] FROM [your_table_name_goes_here]">
</asp:SqlDataSource>

VB.net: Accessing data from DataList in Page_Load

New to VB.net, and trying to re-factor an 'old-skool' ASP page where all the page logic is happening on the .aspx page itself, to code-behind. Basically, I have a button that has a state, either on or off. If on, I set a hidden field to 1, if off, I set it to 0 (the default when a user visits the page).
The goal is to simply change the message I am sending to the user.
Have the following relevant code in MyPage.aspx:
<asp:HiddenField ID="hfldState" runat="server" Visible="false" Value="0" />
<div id="mainContent">
<asp:Literal ID="lblMessage" runat="server"
Visible="false" />
<asp:DataList ID="dlList" runat="server"
DataSourceID="sdsList"
DataKeyField="Entry No_"
RepeatLayout="Flow">
<ItemTemplate>
<div>
<asp:HyperLink ID="hlCurriculum" runat="server"
Text='<%# DataBinder.Eval(Container.DataItem, "Title") %>'
NavigateUrl='<%# DataBinder.Eval(Container.DataItem, "File Path") %>'
ToolTip='<%# DataBinder.Eval(Container.DataItem, "Title") %>'
Target="_blank"
Style="font-weight: bold;">
</asp:HyperLink>
</div>
</ItemTemplate>
</asp:DataList>
</div>
<asp:SqlDataSource ID="sdsList" runat="server"
ConnectionString="..."
SelectCommand="SELECT [Entry No_], [Title], [File Path] FROM [Table] WHERE ([State] = #State)">
<SelectParameters>
<asp:ControlParameter ControlID="hfldState" Name="State" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
And the following in the Page_Load Sub:
If Page.IsPostBack Then
' Check for results
dlList.DataBind()
If dlList.Items.Count > 0 Then
' Results, display them
lblMessage.Text = "<h3>Results</h3>"
lblMessage.Visible = True
Else
' No results
lblMessage.Text = "<p>No Results</p>"
lblMessage.Visible = True
End If
Else
' user has not clicked anything
lblMessage.Text = "<p>Click button!</p>"
End If
The above code produces the following effect: when I click the button, setting the state to 1 and the page reloads, in Page_Load, I am getting zero results from the If dlList.Items.Count > 0 Then check, and thus am showing the 'No results' message, but the actual asp:DataList on the MyPage.aspx page is returning results... and then if I click the button again, setting it back to 0, in Page_Load, the datalist is now returning results, so I set the text to 'Results', but again, the control on the MyPage.aspx page behaves correctly, and shows no results, as expected. Now keep in mind that the above works perfectly in terms of checking the number of results if I move the If dlList.Items.Count > 0 Then page logic out of Page_Load and back to the MyPage.aspx file, it all works fine (i.e. results when state = 1, none when state = 0)
Any ideas?
I dont see a check in your page load for a postback:
If Not IsPostBack
'code
dList.DataBind() 'here is where you want to bind the data...
end if
The issue related to my ignorance of the page lifecycle in VB.net. Solution was to adjust the visibility of the asp:Literal, asp:DataList, set values etc in Page_PreRenderComplete. Basically, the asp:DataList wasn't being set in Page_Load, as expected, so doing any kind of logic in Page_Load based on the item count didn't make any sense.