Display logged in user asp.net - asp.net

I have made a little custom log-in page in asp.net, see code:
Dim strCon As String = ConfigurationManager.ConnectionStrings("Goed").ConnectionString
'Create Connection String And SQL Statement
Dim strSelect As String = "SELECT COUNT(*) FROM tbl_LogIn WHERE Gebruiker = #Gebruiker AND Wachtwoord = #Wachtwoord"
Dim con As New SqlConnection(strCon)
Dim cmd As New SqlCommand()
cmd.Connection = con
cmd.CommandType = CommandType.Text
cmd.CommandText = strSelect
Dim Gebruiker As New SqlParameter("#Gebruiker", _
SqlDbType.VarChar)
Gebruiker.Value = TxtUs.Text.Trim().ToString()
cmd.Parameters.Add(Gebruiker)
Dim Wachtwoord As New SqlParameter("#Wachtwoord", _
SqlDbType.VarChar)
Wachtwoord.Value = TxtPw.Text.Trim().ToString()
cmd.Parameters.Add(Wachtwoord)
con.Open()
Dim result As Integer = DirectCast(cmd.ExecuteScalar(), Int32)
con.Close()
If result >= 1 Then
Response.Redirect("default.aspx")
Else
lblMsg.Text = "Gebruikers naam en of wachtwoord kloppen niet"
End If
End Sub
As you can see it directs to Default.aspx.
On my defaults.aspx page I have a header. In this header I want a small label to sdhow the logged in user something like: Hello [User] How can this be done?

Using Sessions:
While Directing to new page (at Login.aspx-in button's onClick event)
Session["valueName"]=value;
On new page( default.aspx in your case) use:
Label1.Text=Session["valueName"].ToString();
Or you can use cookies as well:
CREATE:
Response.Cookies("userInfo")("userName") = "DiederikEEn"
Response.Cookies("userInfo")("lastVisit") = DateTime.Now.ToString()
Response.Cookies("userInfo").Expires = DateTime.Now.AddDays(1)
READING:
If Not Request.Cookies("userName") Is Nothing Then
Label1.Text = Server.HtmlEncode(Request.Cookies("userName").Value)
End If
If Not Request.Cookies("userName") Is Nothing Then
Dim aCookie As HttpCookie = Request.Cookies("userName")
Label1.Text = Server.HtmlEncode(aCookie.Value)
End If
More here:
Cookies
Sessions

If you can create header in your master page then you can add Hello [User] there and call the session.

Related

Procedure expects #location parameter which was not supplied. It is driving me nuts

I know this thread will probably get flagged as duplicate but I have reviewed all similar posts but none seems to help resolve this issue:
I have this code snip:
Dim loc As String = DirectCast(GridView1 _
.FooterRow.FindControl("txtLocation"), TextBox).Text
cmd.CommandText = "insert into Locations(Location " & _
") values(#Location);" & _
"select LocationID, Location from locations"
cmd.Parameters.AddWithValue("#Location", SqlDbType.VarChar).Value = loc
Just to keeping it simple.
This works great.
Then I turned this inline code into stored procedure:
ALTER PROCEDURE [dbo].[spx_AddNewLoc]
#Location varchar(150)
AS
set nocount on
BEGIN --add new request type
INSERT INTO Locations(Location)VALUES(#Location)
SELECT LocationID, Location from locations
END
set nocount off
Then called it in my codefile:
Dim loc As String = DirectCast(GridView1 _
.FooterRow.FindControl("txtLocation"), TextBox).Text
cmd.CommandText = "spx_AddNewLoc "
cmd.Parameters.AddWithValue("#Location", SqlDbType.VarChar).Value = loc
I just keep getting "Procedure expects #location which was not supplied."
Any ideas what I am missing?
<FooterTemplate>
    <asp:TextBox ID="txtlocation" runat="server" placeholder="Please enter location here..." style="width:400px;"></asp:TextBox><br />
</FooterTemplate>
<FooterTemplate>
<asp:Button ID="btnAdd" runat="server" Text="Add" OnClick = "AddNewLocation" />
</FooterTemplate>
'//** latest code below
Protected Sub AddNewLocation(ByVal sender As Object, ByVal e As EventArgs)
Dim IsAdded As Boolean = True
Dim loc As String = DirectCast(GridView1 _
.FooterRow.FindControl("txtLocation"), TextBox).Text
Dim con As New SqlConnection(strConnString)
Dim cmd As New SqlCommand()
cmd.CommandType = CommandType.Text
cmd.CommandText = "insert into Locations(Location " & _
") values(#Location);" & _
"select LocationID, Location from locations"
cmd.Parameters.Add("#Location", SqlDbType.VarChar).Value = loc
If IsAdded = True Then
lblMsg.Text = (Convert.ToString("'") & loc) + "' location added successfully!"
lblMsg.ForeColor = System.Drawing.Color.Green
Else
lblMsg.Text = (Convert.ToString("Error while adding '") & loc) + "' locaton!"
lblMsg.ForeColor = System.Drawing.Color.Red
End If
GridView1.DataSource = GetData(cmd)
GridView1.DataBind()
End Sub
The reason for the error is because you have not set the CommandType to use CommandType.StoredProcedure. I have mocked up both examples to highlight this error.
This is the code prior to me setting the CommandType:
This is the code once I had set the CommandType:
This is the working code:
Using con As New SqlConnection(strConnString),
cmd As New SqlCommand With {.CommandText = "spx_AddNewLoc", .CommandType = CommandType.StoredProcedure,
.Connection = con}
cmd.Parameters.Add("#Location", SqlDbType.VarChar).Value = location
con.Open()
cmd.ExecuteNonQuery()
End Using
Quickly translated from C#. I've tested it locally and it works. You should eventually wrap the code in a Using block to dispose and close the objects/connection properly.
Dim loc As String = "test"
Dim Command As New SqlCommand("spx_AddNewLoc")
Command.Parameters.Add("#Location", SqlDbType.VarChar).Value = loc
Dim Connection As New SqlConnection(connStr)
Command.Connection = Connection
Command.CommandType = CommandType.StoredProcedure
Connection.Open()
Command.ExecuteNonQuery()
Connection.Close()
C#
string storedProcedure = "spx_AddNewLoc";
string location = "Amsterdam";
using (SqlConnection connection = new SqlConnection(connStr))
using (SqlCommand command = new SqlCommand(storedProcedure, connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#Location", SqlDbType.VarChar).Value = location;
connection.Open();
command.ExecuteNonQuery();
}
As far as you have changed it to a Stored Procedure, you should change .CommandType of your SqlCommand.
cmd.CommandType = CommandType.StoredProcedure;
SqlCommand.CommandType Property
Rename AddWithValue to Add. In your code AddWithValue accepts value as second param and I suspect it makes your parameter #Location of other type than varchar, that's why it cannot be found on a procedure execute. https://msdn.microsoft.com/en-us/library/wbys3e9s(v=vs.110).aspx

Activation Email/Link Not Working

I'm trying to send an activation email and have the user activate their account by clicking on the link provided. I have been tweaking it based on open source code I've been looking at online, however it has recently stopped sending the email without giving any errors. Here is the sign up form with the send email function:
Imports System.Data.SqlClient
Imports System.Data.Sql
Imports System.Data.SqlTypes
Imports System.Data
Imports System.Configuration
Imports System.Net.Mail
Imports System.Net
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Public Class WebForm1
Inherits System.Web.UI.Page
Dim boolCar As Object
Private Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
If txtEmailAddress.Text.Trim.EndsWith("#umary.edu") Or txtPassword.Text.Trim = txtRetypePassword.Text.Trim Then
Dim con As New SqlConnection
Dim cmdEmail As New SqlCommand
Dim cmdRegistration As New SqlCommand
Dim EmailCount As Integer = 0
Try
con.ConnectionString = "Data Source=SERVERNAME;Initial Catalog=StudentGov;User ID=sa;Password=Password1"
con.Open()
cmdEmail = New SqlCommand("SELECT COUNT(UMaryEmail) As EmailCount FROM RegisteredUsers WHERE UMaryEmail='" & txtEmailAddress.Text.Trim & "'", con)
EmailCount = cmdEmail.ExecuteScalar()
If EmailCount = 0 Then
' Declare database input variables
Dim userId As Integer = 0
Dim firstName As String = txtFirstName.Text
Dim lastName As String = txtLastName.Text
Dim hometown1 As String = txtHometown1.Text
Dim state1 As String = txtState1.Text
Dim zip1 As String = txtZipCode1.Text
Dim hometown2 As String = txtHometown2.Text
Dim state2 As String = txtState2.Text
Dim zip2 As String = txtZipCode2.Text
Dim phoneNum As String = txtPhoneNumber.Text
Dim emailAddress As String = txtEmailAddress.Text
Dim password As String = txtPassword.Text
Dim boolCar As Boolean = False
Dim boolUmary As Boolean = False
If radYesNo.SelectedIndex = 0 Then
boolCar = True
Else
boolCar = False
End If
' Define the command using parameterized query
cmdRegistration = New SqlCommand("INSERT INTO RegisteredUsers(FirstName, LastName, Hometown1, State1, ZIP1, Hometown2, State2, ZIP2, PhoneNum, UMaryEmail, Password, Car) VALUES (#txtFirstName, #txtLastName, #txtHometown1, #txtState1, #txtZipCode1, #txtHometown2, #txtState2, #txtZipCode2, #txtPhoneNumber, #txtEmailAddress, #txtPassword, #RadYesNo)", con)
' Define the SQL parameter '
cmdRegistration.Parameters.AddWithValue("#txtFirstName", txtFirstName.Text)
cmdRegistration.Parameters.AddWithValue("#txtLastName", txtLastName.Text)
cmdRegistration.Parameters.AddWithValue("#txtHometown1", txtHometown1.Text)
cmdRegistration.Parameters.AddWithValue("#txtState1", txtState1.Text)
cmdRegistration.Parameters.AddWithValue("#txtZipCode1", txtZipCode1.Text)
cmdRegistration.Parameters.AddWithValue("#txtHometown2", txtHometown2.Text)
cmdRegistration.Parameters.AddWithValue("#txtState2", txtState2.Text)
cmdRegistration.Parameters.AddWithValue("#txtZipCode2", txtZipCode2.Text)
cmdRegistration.Parameters.AddWithValue("#txtPhoneNumber", txtPhoneNumber.Text)
cmdRegistration.Parameters.AddWithValue("#txtEmailAddress", txtEmailAddress.Text)
cmdRegistration.Parameters.AddWithValue("#txtPassword", txtPassword.Text)
cmdRegistration.Parameters.AddWithValue("#RadYesNo", boolCar)
cmdRegistration.ExecuteNonQuery()
SendActivationEmail(userId)
Response.Redirect("RegistrationSuccess.aspx")
Else
' Duplicate Email Exist Error Message
MsgBox("Email address already supplied.")
End If
' Catch ex As Exception (Not needed)
' Error Executing One Of The SQL Statements
Finally
con.close()
End Try
Else
' Throw Error Message
MsgBox("Email input error")
End If
End Sub
Private Sub SendActivationEmail(userId As Integer)
Dim sqlString As String = "Server=SERVERNAME;Database=StudentGov;UId=sa;Password=Password1;"
Dim ActivationCode As String = Guid.NewGuid().ToString()
Dim ActivationUrl As String = Server.HtmlEncode("http://localhost:63774/ActivateAccount.aspx?userId=" & FetchUserId(txtEmailAddress.ToString) & "&txtEmailAddress=" & txtEmailAddress.ToString & "&ActivationCode=" & ActivationCode.ToString)
Using con As New SqlConnection(sqlString)
Using sqlCmd As New SqlCommand("UPDATE RegisteredUsers SET UserId = '" + userId.ToString + "', ActivationCode = '" + ActivationCode.ToString + "' WHERE UMaryEmail='" + txtEmailAddress.Text + "';")
Using sda As New SqlDataAdapter()
sqlCmd.CommandType = CommandType.Text
sqlCmd.Parameters.AddWithValue("#UserId", userId)
sqlCmd.Parameters.AddWithValue("#ActivationCode", ActivationCode)
sqlCmd.Connection = con
con.Open()
sqlCmd.ExecuteNonQuery()
con.Close()
End Using
End Using
End Using
Using mm As New MailMessage("****#outlook.com", txtEmailAddress.Text)
mm.Subject = "Account Activation"
Dim body As String = "Hello " + txtFirstName.Text.Trim() + ","
body += "<br /><br />Please click the following link to activate your account"
body += "<br /><a href='" & ActivationUrl & "'>Click here to activate your account.</a>"
body += "<br /><br />Thanks"
mm.Body = body
mm.IsBodyHtml = True
Dim smtp As New SmtpClient()
smtp.Host = "smtp.live.com"
smtp.EnableSsl = True
Dim NetworkCred As New NetworkCredential("****#outlook.com", "****")
smtp.UseDefaultCredentials = True
smtp.Credentials = NetworkCred
smtp.Port = 587
Try
smtp.Send(mm)
Catch ex As Exception
MsgBox("Email was not sent")
End Try
End Using
End Sub
Private Function FetchUserId(emailAddress As String) As String
Dim cmd As New SqlCommand()
Dim con As New SqlConnection("Data Source=SERVERNAME;Initial Catalog=StudentGov;User ID=sa;Password=Password1")
cmd = New SqlCommand("SELECT UserId FROM RegisteredUsers WHERE UMaryEmail=#txtEmailAddress", con)
cmd.Parameters.AddWithValue("#txtEmailAddress", emailAddress)
If con.State = ConnectionState.Closed Then
con.Open()
End If
Dim userId As String = Convert.ToString(cmd.ExecuteScalar())
con.Close()
cmd.Dispose()
Return userId
End Function
End Class
And here is the AccountActivation page:
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Public Class ActivateAccount
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
ActivateMyAccount()
End If
End Sub
Private Sub ActivateMyAccount()
Dim con As New SqlConnection()
Dim cmd As New SqlCommand()
Try
con.ConnectionString = "Data Source=CISWEB\UMCISSQL2008;Initial Catalog=StudentGov;User ID=sa;Password=Password1"
If (Not String.IsNullOrEmpty(Request.QueryString("UserId"))) And (Not String.IsNullOrEmpty(Request.QueryString("UMaryEmail"))) Then
'approve account by setting Is_Approved to 1 i.e. True in the sql server table
cmd = New SqlCommand("UPDATE RegisteredUsers SET AccountActivated=1 WHERE UserId=#UserId AND UMaryEmail=#txtEmailAddress", con)
cmd.Parameters.AddWithValue("#UserId", Request.QueryString("UserId"))
cmd.Parameters.AddWithValue("#txtEmailAddress", Request.QueryString("UMaryEmail"))
If con.State = ConnectionState.Closed Then
con.Open()
End If
cmd.ExecuteNonQuery()
Response.Write("You account has been activated. You can <a href='SignIn.aspx'>Sign in</a> now! ")
End If
Catch ex As Exception
ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('Error occured : " & ex.Message.ToString() & "');", True)
Return
Finally
con.Close()
cmd.Dispose()
End Try
End Sub
End Class
As you may be able to tell already, I am flummoxed. With no error messages I'm receiving, I don't know why the SendActivationEmail function is no longer working. Someone help please! :(
Hi FlummoxedUser are you sure that have you checked your code as well ????
Take a look here :
Dim ActivationUrl As String = Server.HtmlEncode("http://localhost:63774/ActivateAccount.aspx?userId=" & FetchUserId(txtEmailAddress.ToString) & "&txtEmailAddress=" & txtEmailAddress.ToString & "&ActivationCode=" & ActivationCode.ToString)
I think is better use httputility.urlEncode/Decode for this stuff where it use it to filter only the result of each function or single variable.
Second one take care at your code above
this is in your page :
If (Not String.IsNullOrEmpty(Request.QueryString("UserId"))) And (Not String.IsNullOrEmpty(Request.QueryString("UMaryEmail")))
where have you found "UmaryEmail" key in your querystring parameters?????
Check it and you will solve your issue but check also in cmd and so on in activation page or you will make some issues :)
I hope it help you and if it solves your issue mark this as answer.
UPDATE :
> Dim ActivationUrl As String = Server.HtmlEncode("http://localhost:63774/ActivateAccount.aspx?userId=" & FetchUserId(txtEmailAddress.ToString) & "&txtEmailAddress=" & txtEmailAddress.ToString & "&ActivationCode=" & ActivationCode.ToString)
with this task you create yout activation link which will be something like
http://localhost:63774/ActivateAccount.aspx?userId=1&txtEmailAddress=email#pippo&ActivationCode=123456
Now what's append when click on that link server handle request and create a collection data which include all the keys within your querystring
In effect you can use request.QueryString to check/retrieve values from each keys. So you can use as you did request.Querystring("keyname") to get the value for that particular parameter BUT in your case you check for a key which are not passed into the link. Pay attention that you have setup only 3 keys which are
UserID
txtEmailAddress
ActivationCode
there's no "UMaryEmail" key in request query string
Also another important stuff NEVER PASS IN QUERY STRING DATABASE FIELD :) use fantasy name or shortname which not reflect database field
example :
UserID => uid
ActivatioCode = token,acd,cd or anything you want
txtEmailAddress= email, em or any other name
Now activation page issue when you try to check your value use an if statement where check for userid key and UMaryEmail where userid could be matched coz it exist in query string but UmaryEmail is not into the request.querystring you have not provided it so if fails and nothing has been shown in page.
Here your Activation Sub revisited with some comments to better understand :
Private Sub ActivateMyAccount()
'Checking you keys in querystring
If Request.QueryString.AllKeys.Contains("Userid") AndAlso Request.QueryString.AllKeys.Contains("txtEmailAddress") Then
'here we assume that keys exist and so we can proceed with rest
If (Not String.IsNullOrEmpty(Request.QueryString("UserId"))) And (Not String.IsNullOrEmpty(Request.QueryString("txtEmailAddress"))) Then
'no we can proceed to make other stuff
'Another stuff place you connection string within connection string section in webconfig in order to make a simple request like this one :
'classic example for create a connection with web config file
' Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("yourconnectionstringname").ToString)
Using con As New SqlConnection("Data Source=CISWEB\UMCISSQL2008;Initial Catalog=StudentGov;User ID=sa;Password=Password1")
If con.State = ConnectionState.Closed Then con.Open()
Dim sqlQuery As String = "UPDATE RegisteredUsers SET AccountActivated=1 WHERE UserId=#UserId AND UMaryEmail=#txtEmailAddress"
Using cmd As New SqlCommand(sqlQuery, con)
Try
With cmd
.Parameters.AddWithValue("#UserId", Request.QueryString("UserId"))
.Parameters.AddWithValue("#txtEmailAddress", Request.QueryString("txtEmailAddress"))
.ExecuteNonQuery()
Response.Write("You account has been activated. You can <a href='SignIn.aspx'>Sign in</a> now! ")
End With
Catch ex As Exception
ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('We apologize but something is gone wrong;our techs are checking the issue.Best regards etc etc etc');", True)
End Try
End Using
End Using
Else
Response.Write("<h1>invalid activation links!!</h1>")
End If
Else
Response.Write("<h1>invalid activation links!!</h1>")
End If
End Sub
If your query is right it should work at first shot :)
Take a try and let me know and if it solve your issue please mark it as answer
UPDATE 2:
Your actual code is :
Dim ActivationUrl As String = Server.HtmlEncode("localhost:63774/ActivateAccount.aspx?userId=" & HttpUtility.UrlEncode(FetchUserId(txtEmailAddress.ToString)) & "&txtEmailAddress=" & HttpUtility.UrlEncode(txtEmailAddress.ToString) & "&ActivationCode=" & HttpUtility.UrlEncode(ActivationCode.ToString))
But is all wrong let me explain:
Declar your variable : Dim ActivationUrl as string it is ok
Then built url so :
="http://localhost:63774/ActivateAccount.aspx?userId=" & HttpUtility.UrlEncode(FetchUserId(txtEmailAddress.text.tostring)) & "&txtEmailAddress=" & HttpUtility.UrlEncode(txtEmailAddress.text.tostring) & "&ActivationCode=" & HttpUtility.UrlEncode(ActivationCode.ToString))
Where take a look to piece of code which is your : 'HttpUtility.UrlEncode(txtEmailAddress.ToString)' in this manner you are passing a value system type object which is a textbox to pass textbox value you need to access to its .Text property like txtEmailAddress .Text
Change as per my code above and it will work (if your procedure is right)
**UPDATE CODE 3 **
Change your code with this.§be carefull don't change anything copy and paste all ActivateMyAccount Sub and delete your old one
Private Sub ActivateMyAccount()
'Checking you keys in querystring
If Request.QueryString.AllKeys.Contains("userId") And Request.QueryString.AllKeys.Contains("txtEmailAddress") Then
'here we assume that keys exist and so we can proceed with rest
If (Not String.IsNullOrEmpty(Request.QueryString("userId"))) And (Not String.IsNullOrEmpty(Request.QueryString("txtEmailAddress"))) Then
'no we can proceed to make other stuff
'Another stuff place you connection string within connection string section in webconfig in order to make a simple request like this one :
'classic example for create a connection with web config file
' Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("yourconnectionstringname").ToString)
Using con As New SqlConnection("Data Source=CISWEB\UMCISSQL2008;Initial Catalog=StudentGov;User ID=sa;Password=Password1")
If con.State = ConnectionState.Closed Then con.Open()
Dim sqlQuery As String = "UPDATE RegisteredUsers SET AccountActivated=1 WHERE UserId=#UserId AND UMaryEmail=#txtEmailAddress"
Using cmd As New SqlCommand(sqlQuery, con)
Try
With cmd
cmd.Parameters.AddWithValue("#UserId", Request.QueryString("userId"))
cmd.Parameters.AddWithValue("#txtEmailAddress", Request.QueryString("txtEmailAddress"))
cmd.ExecuteNonQuery()
Response.Write("You account has been activated. You can <a href='SignIn.aspx'>Sign in</a> now! ")
End With
Catch ex As Exception
ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('We apologize but something is gone wrong;our techs are checking the issue.Best regards etc etc etc');", True)
End Try
End Using
End Using
Else
Response.Write("<h1>invalid activation links!! bad query string</h1>")
End If
Else
Response.Write("<h1>invalid activation links!! bad not string</h1>")
End If
End Sub

How to use ASPxFileManager 'SelectedFiles' property to attach files to MailMessage?

I am using DevExpress tools, specifically the FileManager which has a 'SelectedFiles' property which returns all the data needed to (add,insert,delete,retrieve, modify the record). However I can not figure out how to use the selectedfiles as a MailMessage.Attachment. The code below works to send the email, I've changed the credentials and host values for security. I just need some direction or thought on how to use the FileManager collection that is generated via 'SelectedFiles' and add them as an attachment to the email. I would really like to Zip the files if possible, but at this point simply attaching them is fine. Any thoughts?
Dim fileManager As ASPxFileManager = TryCast(sender, ASPxFileManager)
If ASPxFileManager1.SelectedFiles IsNot Nothing AndAlso ASPxFileManager1.SelectedFiles.Length > 0 Then
For i As Integer = 0 To ASPxFileManager1.SelectedFiles.Length - 1
Dim file = ASPxFileManager1.SelectedFiles.ToString
Dim attachments As New Attachment(fileManager.SelectedFiles.ToString)???
Next
End If
Try
Dim mail As New MailMessage("noreply", DropDownEdit.Text)
Dim smtp_Server As New SmtpClient("host") With {.Credentials = New Net.NetworkCredential("username", "password")}
mail.Subject = "SUBJECT"
mail.IsBodyHtml = False
mail.Body = "Testing"
smtp_Server.Send(mail)
successLabel.Text = "Your email was sent successfully."
Catch ex As Exception
End Try
End Sub
Dim attachments As New Attachment(ReadFile(ASPxFileManager1.SelectedFiles(i)), file)
mail.Attachments.Add(attachments)
The function below was needed to Read the bytes and then attach the items to the MailMessage.
Public Function ReadFile(file__1 As FileManagerFile) As System.IO.Stream
'This function allows us to pull the bytes from the DB value to render the file.
Dim filePath As String = (file__1.RelativeName)
Dim fileData As Byte()
Using con As New SqlConnection([Global].conn)
Dim sqlCmd As New SqlCommand()
sqlCmd.Connection = con
sqlCmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = file__1.Name
sqlCmd.Parameters.Add("#APIKey", SqlDbType.Int).Value = Session("_UserAPIKey")
sqlCmd.CommandText = "SELECT STATEMENT"
con.Open()
Dim sqlReader As SqlDataReader = sqlCmd.ExecuteReader()
If sqlReader.HasRows Then
While sqlReader.Read()
fileData = CType(sqlReader(0), Byte())
End While
End If
End Using
Return New MemoryStream(fileData)
End Function

how to display an image from database?

i know too that this (kind of) question has been asked and answered many times. I myself have asked this once before. But I havnt been successful yet. how do I display the image in an image control for a particular employee ID... Heres my code:
`
bind()
GridView1.Visible = "True"
Dim strQuery As String = "SELECT Image FROM EmployeeTable WHERE EmployeeID =#EmployeeID"
Dim cmd As SqlCommand = New SqlCommand(strQuery)
cmd.Parameters.Add("#EmployeeID", SqlDbType.Int).Value() = Convert.ToInt32(Request.QueryString("ImageID"))
Dim dt As DataTable = GetData(cmd)
If dt IsNot Nothing Then
**Dim bytes() As Byte = CType(dt.Rows(1)("Image"), Byte())**
Response.Buffer = True
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = dt.Rows(0)("ContentType").ToString()
Response.AddHeader("content-disposition", "attachment;filename=" + dt.Rows(1)("Name").ToString())
Response.BinaryWrite(bytes)
Response.Flush()
Response.End()
End If`
Getting error at the line in bold. "There is no row at position 1"...
Actually I want to fetch (display) the image for a particular employee id. How does it concern a row position? I dont know why i have written that line of code. Anyway, I know there are guys who can help me with this and so I thank them in advance...
OK, Heres my code for adding the image to the database. This is working fine.
Dim imageData As Byte() = New Byte(FileUpload1.FileContent.Length) {}
FileUpload1.FileContent.Read(imageData, 0, Convert.ToInt32(FileUpload1.FileContent.Length))
Dim con As New SqlConnection(System.Configuration.ConfigurationManager.AppSettings("ConnectionString").ToString)
con.Open()
If EmployeeIDTextBox.Text = "" Then
MsgBox("Please Enter EmployeeID to Add Photo")
Else
Dim com As New SqlCommand("UPDATE EmployeeTable SET IMAGE = #IM where EmployeeID='" & EmployeeIDTextBox.Text & "'", con)
Dim filePath As String = Server.MapPath(FileUpload1.FileName)
'Dim imageData As Byte() = File.ReadAllBytes(filePath)
com.Parameters.AddWithValue("#IM", imageData)
com.ExecuteNonQuery()
MsgBox("File Saved Successfully!")
End If
End Sub
And now this is my code for retrieving & displaying the same image in an image control...
bind()
GridView1.Visible = "True"
'If Request.QueryString("ImageID") IsNot Nothing Then
Dim strQuery As String = "SELECT Image FROM EmployeeTable WHERE EmployeeID =#EmployeeID"
Dim cmd As SqlCommand = New SqlCommand(strQuery)
cmd.Parameters.Add("#EmployeeID", SqlDbType.Int).Value() = Convert.ToInt32(Request.QueryString("Image"))
Dim dt As DataTable = GetData(cmd)
If dt IsNot Nothing Then
Dim bytes() As Byte = CType(dt.Rows(0)("Image"), Byte())
Response.Buffer = True
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = dt.Rows(0)("ContentType").ToString()
Response.AddHeader("content-disposition", "attachment;filename=" + dt.Rows(1)("Name").ToString())
Response.BinaryWrite(bytes)
Response.Flush()
Response.End()
End IF
This is not working...
Array indexes start from 0
Use
Dim bytes() As Byte = CType(dt.Rows(0)("Image"), Byte())
How is it that you don't know why you have written that?
The code you have will prompt a user to save the image file on his pc.
It will not show the image in an image control.
U can use a Http Handler and use the below code in ProcessRequest()
int Id = Convert.ToInt32(Request.QueryString["ImgId"]);
using (var conn = new SqlConnection(connectionString))
using (var command = new SqlCommand(
"SELECT ImageFile FROM ImageTable WHERE ImageId = #ImgId", conn))
{
command.Parameters.Add("#ImgId", SqlDbType.Int).Value = Id ;
conn.Open();
Response.ContentType = "image/gif"; //u can set it per ur requirement
Response.BinaryWrite((byte[]) command.ExecuteScalar());
}
and then use image in your page as :
<asp:Image id="Img_Db" runat="server" ImageUrl="Image.ashx?ImgId=1"/>

Help with asp login SQL

I have a form which goes to the following login script when it is submitted.
<%
Dim myConnection As System.Data.SqlClient.SqlConnection
Dim myCommand As System.Data.SqlClient.SqlCommand
Dim requestName As String
Dim requestPass As String
requestName = Request.Form("userName")
requestPass = Request.Form("userPass")
Dim queryString As String = "SELECT COUNT(*) AS Num_Of_User FROM tblusers WHERE username='" & requestName & "' AND password='" & requestPass & "'"
myConnection = New System.Data.SqlClient.SqlConnection("Data Source=(local);InitialCatalog=dbtest;Integrated Security=True")
myCommand = New System.Data.SqlClient.SqlCommand(queryString, myConnection)
myConnection.Open()
Dim reader As System.Data.SqlClient.SqlDataReader = myCommand.ExecuteReader()
%>
Now in theory, I should be able to get that Num_Of_User from the SQL Query and if it equals 1 than the login was successful. Is this the correct way? And how can I get the value that the SQL returns?
You are wide open to SQL injection using that code.
See happens if you enter the username as ' OR 2>1--
You need to change the to use a parametrized query.
Dim queryString As String = "SELECT COUNT(*) AS Num_Of_User FROM tblusers WHERE username=#username AND password=#password"
myConnection = New System.Data.SqlClient.SqlConnection("Data Source=(local);InitialCatalog=dbtest;Integrated Security=True")
myCommand = New System.Data.SqlClient.SqlCommand(queryString, myConnection)
myCommand.Parameters.AddWithValue("#username", requestName)
myCommand.Parameters.AddWithValue("#password", requestPass)
Also you are not handling any exceptions that might be thrown, nor disposing your objects.
Your code should look more like the following.
Dim numUsers as Integer
Using myConnection as New System.Data.SqlClient.SqlConnection("Data Source=(local);InitialCatalog=dbtest;Integrated Security=True")
Dim queryString As String = "SELECT COUNT(*) AS Num_Of_User FROM tblusers WHERE username=#username AND password=#password"
Using myCommand as New System.Data.SqlClient.SqlCommand(queryString, myConnection)
myConnection.Open
myCommand.Parameters.AddWithValue("#username", requestName)
myCommand.Parameters.AddWithValue("#password", requestPass)
numUsers = myCommand.ExecuteScalar()
End Using
End Using
The above code will make sure your objects are disposed, but won't handle any exceptions that might be thrown.
Try myCommand.ExecuteScalar(), which returns the value from the first column in the first row of the resultset - exactly the value you're after here.
Also, check into the ASP.Net 'built in' authentication methods - this might save you some effort.

Resources