cannot display image in image control - asp.net

Its my handler (.ashx)
Dim EmployeeID As Integer
If (Not (context.Request.QueryString("EmployeeID")) Is Nothing) Then EmployeeID = Convert.ToInt32(context.Request.QueryString("EmployeeID"))
Else Throw New ArgumentException("No parameter specified") End If
Dim imageData() As Byte = {}
' get the image data from the database using the employeeId Querystring context.Response.ContentType = "image/jpeg"
context.Response.BinaryWrite(imageData)
Everything is working fine.Only the imageData length is 0 so the image is unable to display.
#Sean: its elsewhr.. here the querystring correctly takes the employeeid passed...
heres the code for db access:
Public Sub bind()
Dim ds1 As New DataSet()
Dim con As New SqlConnection(System.Configuration.ConfigurationManager.AppSettings("ConnectionString").ToString)
con.Open()
Dim query As String = "select * from EmployeeTable"
Dim cmd As New SqlCommand()
Dim da1 As New SqlDataAdapter(query, con)
da1.Fill(ds1, "EmployeeTable")
GridView1.DataSource = ds1.Tables("EmployeeTable")
GridView1.DataBind()
con.Close()
End Sub

You're loading a load of data into the GridView but nothing is being loaded into your imageData variable. So we'll just connect to the database and pull that data out. I'm assuming your image column is called imageData but please change as appropriate.
Dim EmployeeID As Integer
If (Not (context.Request.QueryString("EmployeeID")) Is Nothing) Then
EmployeeID = Convert.ToInt32(context.Request.QueryString("EmployeeID"))
Else
Throw New ArgumentException("No parameter specified")
End If
Dim imageData() As Byte = {}
' get the image data from the database using the employeeId Querystring
Using con As New SqlConnection(ConfigurationManager.AppSettings("ConnectionString"))
Using cmd As New SqlCommand("SELECT imageData FROM EmployeeTable WHERE EmployeeID = #EmployeeID", con) 'select imageData column, change column name as appropriate
cmd.Parameters.AddWithValue("#EmployeeID", EmployeeID)
Try
con.Open()
Using rdr As SqlDataReader = cmd.ExecuteReader()
If rdr.Read() Then
imageData = CType(rdr("imageData"), Byte()) 'convert imageData column from result set to byte array and assign to variable
End If
End Using
Catch ex As Exception
'do any error handling here
End Try
End Using
End Using
context.Response.ContentType = "image/jpeg"
context.Response.BinaryWrite(imageData)

Changed the code in the handler to this:
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim EmployeeID As Integer
If (Not (context.Request.QueryString("EmployeeID")) Is Nothing) Then
EmployeeID = Convert.ToInt32(context.Request.QueryString("EmployeeID"))
Else
Throw New ArgumentException("No parameter specified")
End If
Dim Image() As Byte = {}
' get the image data from the database using the employeeId Querystring
Dim con As New SqlConnection(System.Configuration.ConfigurationManager.AppSettings("ConnectionString").ToString)
Dim cmd As New SqlCommand("SELECT Image FROM EmployeeTable WHERE EmployeeID = #EmployeeID", con)
'select imageData column, change column name as appropriate
cmd.Parameters.AddWithValue("#EmployeeID", EmployeeID)
Try
con.Open()
Dim rdr As SqlDataReader = cmd.ExecuteReader()
While rdr.Read()
Image = CType(rdr("Image"), Byte())
'convert imageData column from result set to byte array and assign to variable
End While
Catch ex As Exception
'do any error handling here
End Try
context.Response.ContentType = "image/jpeg"
context.Response.BinaryWrite(Image)
End Sub
Worked for me, may be it will work for you too...

Related

TVP - Failed to convert parameter value from a SqlParameter to a IEnumerable`1

I am trying to create a general purpose function which can accept tvp.
I am getting error 'Failed to convert parameter value from a SqlParameter to a IEnumerable`1.'
Dim param As New SqlParameter("#parName", GetTVP(lstDates))
param.SqlDbType = SqlDbType.Structured
sqlProvider.ExecuteNonQueryV2("sp_Save", CommandType.StoredProcedure, param)
---------------------
Public Function ExecuteNonQuery(ByVal spname As String, ByRef returnValue As Integer, ByVal ParamArray parameterValues() As Object) As Integer
Dim connection As SqlConnection = Nothing
Dim transaction As SqlTransaction = Nothing
Dim command As SqlCommand = Nothing
Dim r As Integer = -1
Try
connection = New SqlConnection(myconnectionString)
command = New SqlCommand(spname, connection)
command.CommandType = CommandType.StoredProcedure
connection.Open()
SqlCommandBuilder.DeriveParameters(command)
Me.SetParameters(command, parameterValues)
transaction = connection.BeginTransaction()
command.Transaction = transaction
r = command.ExecuteNonQuery()
transaction.Commit()
Catch ex As Exception
Finally
End Try
Return r
End Function
---------------------
Private Sub SetParameters(ByVal cmd As SqlCommand, ByVal parameterValues() As Object)
Dim i As Integer
For Each param As SqlParameter In cmd.Parameters
param.Value = parameterValues(i)
i += 1
Next
End Sub
ADDED
I have updated the code and take the "SqlCommandBuilder.DeriveParameters(command)" out and now passing parameter as a sqlparameter list. All works fine now :)
But i like to know why is it working when i have not defined the parameter type to SqlDbType.Structured ? Isn't it required?
Dim par As New List(Of SqlParameter)
par.Add(New SqlParameter("#parName", GetTVP(lstDates))
---------------
connection = New SqlConnection(myconnectionString)
command = New SqlCommand(spname, connection)
command.CommandType = CommandType.StoredProcedure
connection.Open()
Me.SetParameters(command, parameterValues)
transaction = connection.BeginTransaction()
command.Transaction = transaction
r = command.ExecuteNonQuery()
transaction.Commit()
Why don't you pass in the signature a list of SqlParameter instead of a list of objects as parameters?
You can do it this way;
Public Function ExecuteNonQuery(ByVal spname As String,
ByRef returnValue As Integer,
ByRef parameters As List(Of SqlParameter)) As Integer
Then you can loop and add
For Each para As SqlParameter In parameters
command.Parameters.Add(para)
Next
Check this link out http://geekswithblogs.net/Rhames/archive/2008/10/29/why-you-should-always-specify-the-sqldbtype-for-an-ado.net.aspx. Ideally and recommended that you define the parameter type, however it is not mandatory.

Uploading files to SQL Server 2012 with ASP.NET/VB.NET

I followed a tutorial an ran the below code without any errors. The file "uploads", however no data is inserted into my SQL Server table.
Data should be inserted into the content table.
Content Table:
Document.aspx
Imports System.Data.SqlClient
Imports System.Data
Imports System.IO
Partial Class Documents
Inherits System.Web.UI.Page
Protected Sub btnUploadContent_Click(sender As Object, e As EventArgs) Handles btnUploadContent.Click
Dim filePath As String = FileUpload.PostedFile.FileName
Dim filename As String = Path.GetFileName(filePath)
Dim ext As String = Path.GetExtension(filename)
Dim contenttype As String = String.Empty
Select Case ext
Case ".doc"
contenttype = "application/vnd.ms-word"
Exit Select
Case ".docx"
contenttype = "application/vnd.ms-word"
Exit Select
Case ".xls"
contenttype = "application/vnd.ms-excel"
Exit Select
Case ".xlsx"
contenttype = "application/vnd.ms-excel"
Exit Select
Case ".jpg"
contenttype = "image/jpg"
Exit Select
Case ".png"
contenttype = "image/png"
Exit Select
Case ".gif"
contenttype = "image/gif"
Exit Select
Case ".pdf"
contenttype = "application/pdf"
Exit Select
End Select
If contenttype <> String.Empty Then
Dim fs As Stream = FileUpload.PostedFile.InputStream
Dim br As New BinaryReader(fs)
Dim bytes As Byte() = br.ReadBytes(fs.Length)
'insert the file into database
Dim strQuery As String = "INSERT INTO content (content_name, content_type, content_file) VALUES (#Name, #ContentType, #Data)"
Dim cmd As New SqlCommand(strQuery)
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = filename
cmd.Parameters.Add("#ContentType", SqlDbType.VarChar).Value() = contenttype
cmd.Parameters.Add("#Data", SqlDbType.Binary).Value = bytes
InsertUpdateData(cmd)
lblMessage.ForeColor = System.Drawing.Color.Green
lblMessage.Text = "File Uploaded Successfully"
Else
lblMessage.ForeColor = System.Drawing.Color.Red
lblMessage.Text = "File format not recognised." + " Upload Image/Word/PDF/Excel formats"
End If
End Sub
Public Function InsertUpdateData(ByVal cmd As SqlCommand) As Boolean
Dim strConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings("ConnStringDb1").ConnectionString()
Dim conn As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True;")
cmd.CommandType = CommandType.Text
cmd.Connection = conn
Try
conn.Open()
cmd.ExecuteNonQuery()
Return True
Catch ex As Exception
Response.Write(ex.Message)
Return False
Finally
conn.Close()
conn.Dispose()
End Try
End Function
End Class
Can anyone tell me what's going on ?
EDIT: Debug Breakpoint # InsertUpdateData(cmd) :
SqlDbType.Binary Binary {1} System.Data.SqlDbType
+ bytes {Length=4136752} Byte()
+ cmd {System.Data.SqlClient.SqlCommand} System.Data.SqlClient.SqlCommand
+ cmd.Parameters {System.Data.SqlClient.SqlParameterCollection} System.Data.SqlClient.SqlParameterCollection
I have created empty database and added table content just like you have and I used code almost the same as you and it worked fine.
Again, if no exception occurs, please check your connection string and see whether the rows been added to the table in the db specified in connection string.
Here is my code (which is working fine), a bit modified from yours:
Imports System.Data.SqlClient
Imports System.IO
Public Class _Default
Inherits System.Web.UI.Page
Protected Sub btnUploadContent_Click(sender As Object, e As EventArgs) Handles btnTest1.Click
Dim fs As Stream = FileUpload.PostedFile.InputStream
Dim br As New BinaryReader(fs)
Dim bytes As Byte() = br.ReadBytes(fs.Length)
'insert the file into database
Dim strQuery As String = "INSERT INTO content (content_name, content_type, content_file) VALUES (#Name, #ContentType, #Data)"
Dim cmd As New SqlCommand(strQuery)
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = "filename"
cmd.Parameters.Add("#ContentType", SqlDbType.VarChar).Value() = "jpg"
cmd.Parameters.Add("#Data", SqlDbType.Binary).Value = bytes
InsertUpdateData(cmd)
End Sub
Public Function InsertUpdateData(ByVal cmd As SqlCommand) As Boolean
Dim conn As New SqlConnection("Data Source=(local);Initial Catalog=test;Integrated Security=True;")
cmd.CommandType = CommandType.Text
cmd.Connection = conn
Try
conn.Open()
cmd.ExecuteNonQuery()
Return True
Catch ex As Exception
Response.Write(ex.Message)
Return False
Finally
conn.Close()
conn.Dispose()
End Try
End Function
End Class
I add sample of SQL to test on DB:
INSERT INTO [master_db].[dbo].[content]
([content_name]
,[content_type]
,[content_file])
VALUES
('test'
,'png'
,0x111111111111111)
SELECT * FROM [master_db].[dbo].[content]
I came across this post looking looking for an example. I used the example code you posted and had the same problem. I found and resolved the following issues and got it working:
I created the db table as pictured. content_type of nchar(5) was the first problem since you were inserting something like "application/vnd.ms-word" which was too big.
The next error was because I had not defined the content_id to be an identity column and since it wasn't listed in the insert statement it failed.
Next I had an error as my db user didn't have insert privileges.
The biggest problem is that the return message was always a success message because even though the InsertUpdateData function was catching errors it was not notifying the calling code. This made me think things were okay. doh! Using a breakpoint on the ExecuteNonQuery allowed me to see the errors.
Hope that helps the next person that stops by....

How to sort a List?

I have tried to sort the list in many ways, but none work for me. I must be doing something wrong. I want to sort the List details then serialize it and send it to the UI, so that i have a sorted List in the UI.
So basically i want Return strJson to return the sorted(sorted by the sort property) List. Hope i am making sense.
<WebMethod(Description:="Get Home Page Items Page Wise", EnableSession:=True)> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)>
Public Function GetHomePageItemsPageWise(ByVal pageIndex As String) As Object
Dim details As New List(Of HomePageObject)()
Dim idObject As New List(Of GetIdBasedOnInterest)()
idObject = CType(BLL.GetDataByInterests(CType(BLL.GetAccIdFromSocialAuthSession(), Integer)), List(Of GetIdBasedOnInterest))
Dim cmd As DbCommand = _db.GetStoredProcCommand("GetHomePageObjectPageWise")
_db.AddInParameter(cmd, "PageIndex", SqlDbType.VarChar, pageIndex)
_db.AddInParameter(cmd, "PageSize", SqlDbType.Int, 10)
_db.AddOutParameter(cmd, "PageCount", SqlDbType.Int, 1)
_db.AddInParameter(cmd, "whereStoryID", SqlDbType.VarChar, idObject(0).StoryIds)
_db.AddInParameter(cmd, "whereAlbumID", SqlDbType.VarChar, idObject(0).AlbumIds)
_db.AddInParameter(cmd, "wherePictureID", SqlDbType.VarChar, idObject(0).PictureIds)
Try
Using ds As DataSet = _db.ExecuteDataSet(cmd)
For Each rs As DataRow In ds.Tables(0).Rows
Dim homePageObject As New HomePageObject()
homePageObject.AlbumId = rs("AlbumId").ToString()
homePageObject.StoryTitle = rs("StoryTitle").ToString()
homePageObject.AlbumName = rs("AlbumName").ToString()
homePageObject.AlbumCover = rs("AlbumCover").ToString()
homePageObject.Votes = rs("Votes").ToString()
homePageObject.PictureId = rs("PictureId").ToString()
homePageObject.TableName = rs("tableName").ToString()
homePageObject.PageCount = CType(cmd.Parameters("#PageCount").Value, Integer)
homePageObject.Sort = Guid.NewGuid()
details.Add(homePageObject)
Next
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
Dim js As New JavaScriptSerializer()
Dim strJson As String = js.Serialize(details.ToArray)
Return strJson
End Function
To randomize the list you can do the following. (And you do not need the Sort property in HomePageObject to accomplish this)
Dim rnd As new Random()
Dim strJson As String = js.Serialize(details.OrderBy(Function(x) rnd.Next()).ToArray())

query string is throwing exception for being null when its not

Here is whats happening , If the user is logged in - this is called directly from Page_Load
Protected Sub EnterNewTransInDb()
Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("connstring").ConnectionString)
Dim comm As New SqlCommand("INSERT INTO tblRegisterRedirect (RegID , UserID, EventID, TimeStamp) VALUES (#RegID, #UserID, #EventID , getdate()) ;", conn)
Dim RegID As Guid
RegID = Guid.NewGuid()
Dim GIUDuserid As Guid
GIUDuserid = New Guid(HttpContext.Current.Request.Cookies("UserID").Value.ToString())
Dim GIUDevnetid As New Guid(HttpContext.Current.Request.QueryString("id").ToString())
comm.Parameters.AddWithValue("#RegID", RegID)
comm.Parameters.AddWithValue("#UserID", GIUDuserid)
comm.Parameters.AddWithValue("#EventID", GIUDevnetid)
Try
conn.Open()
Dim i As Integer = comm.ExecuteNonQuery()
conn.Close()
Catch ex As Exception
Dim errors As String = ex.ToString()
End Try
Dim URL As String = Request.QueryString("url").ToString()
Response.Redirect(URL + "?aid=854&rid=" + RegID.ToString())
End Sub
This works great, but if their not logged in , then they enter their log-in credentials - this happens on Button_Click event, in the click event I call this function EnterNewTransInDb() , When I run it this time , after logging in - SAME CODE , it throws an exception - Object reference is null - referring to the querystring
Protected Sub btnLogin_Click(sender As Object, e As System.EventArgs) Handles btnLogin.Click
'took out code SqlConnection onnection and SqlDataReader Code
dbCon.Open()
'If Email and PW are found
If dr.Read Then
Dim appCookie As New HttpCookie("UserID")
appCookie.Value = dr("GUID").ToString()
appCookie.Expires = DateTime.Now.AddDays(30)
HttpContext.Current.Response.Cookies.Add(appCookie)
Dim appCookie1 As New HttpCookie("UserName")
appCookie1.Value = dr("UserName").ToString
appCookie1.Expires = DateTime.Now.AddDays(30)
HttpContext.Current.Response.Cookies.Add(appCookie1)
Dim appCookie2 As New HttpCookie("UserEmail")
appCookie2.Value = txtEmail.Text.ToLower()
appCookie2.Expires = DateTime.Now.AddDays(30)
HttpContext.Current.Response.Cookies.Add(appCookie2)
Dim appCookie3 As New HttpCookie("Lat")
appCookie3.Value = dr("GeoLat").ToString()
appCookie3.Expires = DateTime.Now.AddDays(30)
HttpContext.Current.Response.Cookies.Add(appCookie3)
Dim appCookie4 As New HttpCookie("Long")
appCookie4.Value = dr("GeoLong").ToString()
appCookie4.Expires = DateTime.Now.AddDays(30)
HttpContext.Current.Response.Cookies.Add(appCookie4)
Dim appCookie5 As New HttpCookie("City")
appCookie5.Value = dr("City").ToString()
appCookie5.Expires = DateTime.Now.AddDays(30)
HttpContext.Current.Response.Cookies.Add(appCookie5)
Dim appCookie6 As New HttpCookie("State")
appCookie6.Value = dr("State").ToString
appCookie6.Expires = DateTime.Now.AddDays(30)
HttpContext.Current.Response.Cookies.Add(appCookie6)
HttpContext.Current.Response.Cookies("EO_Login").Expires = Now.AddDays(30)
HttpContext.Current.Response.Cookies("EO_Login")("EMail") = txtEmail.Text.ToLower()
Dim sUserData As String = HttpContext.Current.Server.HtmlEncode(HttpContext.Current.Request.Cookies("UserID").Value) & "|" & HttpContext.Current.Server.HtmlEncode(HttpContext.Current.Request.Cookies("UserName").Value) & "|" & HttpContext.Current.Server.HtmlEncode(HttpContext.Current.Request.Cookies("UserEmail").Value)
' Dim sUserData As String = "dbcf586f-82ac-4aef-8cd0-0809d20c70db|scott selby|scottselby#live.com"
Dim fat As FormsAuthenticationTicket = New FormsAuthenticationTicket(1, _
dr("UserName").ToString, DateTime.Now, _
DateTime.Now.AddDays(6), True, sUserData, _
FormsAuthentication.FormsCookiePath)
Dim encTicket As String = FormsAuthentication.Encrypt(fat)
HttpContext.Current.Response.Cookies.Add(New HttpCookie(FormsAuthentication.FormsCookieName, encTicket))
'If Email and Pw are not found
Else
dr.Close()
dbCon.Close()
End If
'Always do this
dr.Close()
sSql = "UPDATE eo_Users SET LastLogin=GETUTCDATE() WHERE GUID=#GUID; "
cmd = New SqlCommand(sSql, dbCon)
cmd.Parameters.AddWithValue("#GUID", HttpContext.Current.Session("UserID"))
cmd.ExecuteNonQuery()
dbCon.Close()
EnterNewTransInDb()
'Dim URL As String = Request.QueryString("url").ToString()
'Response.Redirect(URL + "?aid=854&rid=" + RegID.ToString())
End Sub
Assuming you only want this code to run if there is a valid QueryString, you could put a guard clause at the beginning of the method to simply check if QueryString is null and then perform some other action if this page is called without a QueryString.
Try setting the breakpoints before the call and make sure the variables are assigned values.
Have you tried putting a breakpoint on Dim URL As String = Request.QueryString("url").ToString() line in your code? Maybe you just need to evaluate first the querystring for the 'url' parameter, if it exists; before converting it to a string.

Ado.net ExecuteReader giving duplication while binding with datagrid

I am using below mentioned Ado.net function and resultset bind with grid view, however I am getting the duplicate rows in the resultset.
Please help me out.
Thanks
Private _products As New List(Of Product)
Public Property Products As List(Of BusinessObjects.Product)
Get
Return _products
End Get
Set(ByVal value As List(Of BusinessObjects.Product))
_products = value
End Set
End Property
Public Function GetProductDetails() As List(Of Product)
Dim product As New BusinessObjects.Product
Using connection As New SqlConnection
connection.ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
connection.Open()
Using Command As New SqlCommand("select * from T_product", connection)
Dim rdr As SqlDataReader
rdr = Command.ExecuteReader
While rdr.Read()
product.ProductID = rdr("ProductID")
product.ProductName = rdr("ProductName")
Products.Add(product)
End While
GridView1.DataSource = Products
GridView1.DataBind()
End Using
End Using
Return Products
End Function
You should make Dim product As New BusinessObjects.Product initialization inside while reading from SqlDataReader instance
Set(ByVal value As List(Of BusinessObjects.Product))
_products = value
End Set
End Property
Public Function GetProductDetails() As List(Of Product)
Using connection As New SqlConnection
connection.ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
connection.Open()
Using Command As New SqlCommand("select * from T_product", connection)
Dim rdr As SqlDataReader
rdr = Command.ExecuteReader
While rdr.Read()
Dim product As New BusinessObjects.Product
product.ProductID = rdr("ProductID")
product.ProductName = rdr("ProductName")
Products.Add(product)
End While
GridView1.DataSource = Products
GridView1.DataBind()
End Using
End Using
Return Products
End Function
The problem is you are updating and adding same product every time. Create product object inside the While loop as below.
Public Function GetProductDetails() As List(Of Product)
Using connection As New SqlConnection
connection.ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
connection.Open()
Using Command As New SqlCommand("select * from T_product", connection)
Dim rdr As SqlDataReader
rdr = Command.ExecuteReader
While rdr.Read()
Dim product As New BusinessObjects.Product ' product object create here
product.ProductID = rdr("ProductID")
product.ProductName = rdr("ProductName")
Products.Add(product)
End While
GridView1.DataSource = Products
GridView1.DataBind()
End Using
End Using
Return Prod

Resources