How to display MS-Access OLE Object in Gridview? - asp.net

I am looking to display my MS-Access Database OLE Object in a Gridview using ASP.Net. Here's what I have up to now:
<%# WebHandler Language="VB" Class="Handler3" %>
Imports System
Imports System.Web
Imports System.Data.OleDb
Public Class Handler3 : Implements IHttpHandler
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
context.Response.ContentType = "image/jpeg"
Dim id As Integer = Convert.ToInt32(context.Request.QueryString("Imageid"))
Dim con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & "PivotDb.accdb" & ";")
con.Open()
Dim cmd As OleDbCommand = New OleDbCommand("select Img from imgupload where ID=" & id & "", con)
Dim reader As OleDbDataReader = cmd.ExecuteReader
reader.Read()
Dim image As Byte() = DirectCast(reader(1), Byte())
context.Response.BinaryWrite(image)
reader.Close()
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class

Related

QueryStringModule with FriendlyUrls does not working

Good morning, I need to encrypt my querystring and i found an interesting method in this link and I convert it in vb.net:
Imports System
Imports System.IO
Imports System.Web
Imports System.Text
Imports System.Security.Cryptography
Public Class QueryStringModule
Implements IHttpModule
Public Sub Dispose() Implements IHttpModule.Dispose
End Sub
Public Sub Init(ByVal context As HttpApplication) Implements IHttpModule.Init
AddHandler context.BeginRequest, New EventHandler(AddressOf context_BeginRequest)
End Sub
Private Const PARAMETER_NAME As String = "enc="
Private Const ENCRYPTION_KEY As String = "key"
Private Sub context_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
Dim context As HttpContext = HttpContext.Current
If context.Request.Url.OriginalString.Contains("aspx") AndAlso context.Request.RawUrl.Contains("?") Then
Dim query As String = ExtractQuery(context.Request.RawUrl)
Dim path As String = GetVirtualPath()
If query.StartsWith(PARAMETER_NAME, StringComparison.OrdinalIgnoreCase) Then
Dim rawQuery As String = query.Replace(PARAMETER_NAME, String.Empty)
Dim decryptedQuery As String = Decrypt(rawQuery)
context.RewritePath(path, String.Empty, decryptedQuery)
ElseIf context.Request.HttpMethod = "GET" Then
Dim encryptedQuery As String = Encrypt(query)
context.Response.Redirect(path & encryptedQuery)
End If
End If
End Sub
Private Shared Function GetVirtualPath() As String
Dim path As String = HttpContext.Current.Request.RawUrl
path = path.Substring(0, path.IndexOf("?"))
path = path.Substring(path.LastIndexOf("/") + 1)
Return path
End Function
Private Shared Function ExtractQuery(ByVal url As String) As String
Dim index As Integer = url.IndexOf("?") + 1
Return url.Substring(index)
End Function
Private ReadOnly Shared SALT As Byte() = Encoding.ASCII.GetBytes(ENCRYPTION_KEY.Length.ToString())
Public Shared Function Encrypt(ByVal inputText As String) As String
Dim rijndaelCipher As RijndaelManaged = New RijndaelManaged()
Dim plainText As Byte() = Encoding.Unicode.GetBytes(inputText)
Dim SecretKey As PasswordDeriveBytes = New PasswordDeriveBytes(ENCRYPTION_KEY, SALT)
Using encryptor As ICryptoTransform = rijndaelCipher.CreateEncryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16))
Using memoryStream As MemoryStream = New MemoryStream()
Using cryptoStream As CryptoStream = New CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)
cryptoStream.Write(plainText, 0, plainText.Length)
cryptoStream.FlushFinalBlock()
Return "?" & PARAMETER_NAME & Convert.ToBase64String(memoryStream.ToArray())
End Using
End Using
End Using
End Function
Public Shared Function Decrypt(ByVal inputText As String) As String
Dim rijndaelCipher As RijndaelManaged = New RijndaelManaged()
Dim encryptedData As Byte() = Convert.FromBase64String(inputText)
Dim secretKey As PasswordDeriveBytes = New PasswordDeriveBytes(ENCRYPTION_KEY, SALT)
Using decryptor As ICryptoTransform = rijndaelCipher.CreateDecryptor(secretKey.GetBytes(32), secretKey.GetBytes(16))
Using memoryStream As MemoryStream = New MemoryStream(encryptedData)
Using cryptoStream As CryptoStream = New CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read)
Dim plainText As Byte() = New Byte(encryptedData.Length - 1) {}
Dim decryptedCount As Integer = cryptoStream.Read(plainText, 0, plainText.Length)
Return Encoding.Unicode.GetString(plainText, 0, decryptedCount)
End Using
End Using
End Using
End Function
End Class
but also my project use FriendlyUrls and I figured out that with FriendlyUrls the things does not working and always return the url without the extension ".aspx" but with the querystring not encrypted
Imports System.Web.Routing
Imports Microsoft.AspNet.FriendlyUrls
Public Module RouteConfig
Sub RegisterRoutes(ByVal routes As RouteCollection)
Dim settings As FriendlyUrlSettings = New FriendlyUrlSettings() With {
.AutoRedirectMode = RedirectMode.Permanent
}
routes.EnableFriendlyUrls(settings)
End Sub
End Module
of course if I set .AutoRedirectMode to Off it works but without friendlyurls.
Am I doing something wrong?
EDIT 09/10/2019:
We figured out that remove the test of OriginalString.Contains("aspx") in the context_BeginRequest the encryption works, now the code is like:
Private Sub context_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
Dim context As HttpContext = HttpContext.Current
If context.Request.RawUrl.Contains("?") Then
Dim query As String = ExtractQuery(context.Request.RawUrl)
Dim path As String = GetVirtualPath()
If query.StartsWith(PARAMETER_NAME, StringComparison.OrdinalIgnoreCase) Then
Dim rawQuery As String = query.Replace(PARAMETER_NAME, String.Empty)
Dim decryptedQuery As String = Decrypt(rawQuery)
context.RewritePath(path, String.Empty, decryptedQuery)
ElseIf context.Request.HttpMethod = "GET" Then
Dim encryptedQuery As String = Encrypt(query)
context.Response.Redirect(path & encryptedQuery)
End If
End If
End Sub
But now the question is: there is other method to target an aspx page without test the extension? I think there is a risk that targeting things that not should target like "ashx" or cache-busting code that use querystring.

How do I print to the default printer on my Laptop from a VB.NET app I deployed to a IIS 8 server?

I've developed a VB.Net App using Visual studio 2015 on my Laptop which will print a rdlc local report for each selected row from a Gridview control directly to my laptop's default printer (which is a network printer) using the Microsoft code for 'walkthrough: Printing a Local Report without Preview' (and runs successfully on my local IIS express). When I deploy this App to a virtual company windows 2012 server that has IIS8 running, it no longer sees the default printer on my laptop (and tries to use the default printer on the windows 2012 server). I've searched the web to no success. I assume it's possible because when I use the reportviewer control in other apps I've developed and deployed on the Windows 2012 server, it can see the list of printers from my local laptop. Any ideas?
Here's the relevant VB code I'm using now...
Imports System.Management
Imports System
Imports System.IO
Imports System.Data
Imports System.Data.SqlClient
Imports System.Text
Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.Drawing.Printing
Imports System.Collections.Generic
Imports Microsoft.Reporting.WebForms
Partial Class _Default
Inherits System.Web.UI.Page
Implements IDisposable
Private m_currentPageIndex As Integer
Private m_streams As IList(Of Stream)
Public Shared ViewID As String
Public Shared UserID As String
Public Shared StampID As String
Public Shared GridViewQry As String
Public Shared OpenCntr As Integer = 0
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim sqlConnection2 As New SqlConnection("DataSource=AOXWEBAPP1\SQLEXPRESS;Initial Catalog=ManufacturingApps;User ID=AppUser;Password=#ppus3r;ApplicationIntent=ReadWrite")
Dim cmd2 As New SqlCommand
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1))
Response.Cache.SetNoStore()
OpenCntr = OpenCntr + 1
ViewID = Request.QueryString("ViewID")
If ViewID = "" Then
Response.Redirect("http://AOXWEBAPP1.SCOTT.COM/login/login.aspx")
Else
UserID = Request.QueryString("UserID")
StampID = Request.QueryString("StampID")
End If
cmd2.CommandText = "UpDate Super_FinalChk SET Selected=1 WHERE Printed = 1"
cmd2.Connection = sqlConnection2
sqlConnection2.Open()
cmd2.ExecuteNonQuery()
sqlConnection2.Close()
If OpenCntr = 1 Then
GridViewQry = "SELECT [Printed], [Customer], [AssySN], [Dte], [AssyPartNbr], [Operator], [PrintDate] FROM [Super_FinalChk] ORDER BY [Dte]"
End If
Dim adapter As New SqlDataAdapter(GridViewQry, sqlConnection2)
Dim superfinalchk As New DataSet("SqlDataSource1")
adapter.Fill(superfinalchk, "Super_FinalChkVw")
If (superfinalchk.Tables.Count > 0) Then
PrintATRs.DataSource = superfinalchk
If Not IsPostBack Then
PrintATRs.DataBind()
End If
Else
TextBox1.Text = "Unable to Connect to Database"
End If
' TextBox1.Text = DefaultPrinterName()
End Sub
' Routine to provide to the report renderer, in order to
' save an image for each page of the report.
Private Function CreateStream(ByVal name As String, ByVal fileNameExtension As String, ByVal encoding As Encoding, ByVal mimeType As String, ByVal willSeek As Boolean) As Stream
Dim stream As Stream = New MemoryStream()
m_streams.Add(stream)
Return stream
End Function
' Export the given report as an EMF (Enhanced Metafile) file.
Private Sub Export(ByVal report As LocalReport)
Dim deviceInfo As String = "<DeviceInfo>" &
"<OutputFormat>EMF</OutputFormat>" &
"<PageWidth>8.5in</PageWidth>" &
"<PageHeight>11in</PageHeight>" &
"<MarginTop>0.25in</MarginTop>" &
"<MarginLeft>0.50in</MarginLeft>" &
"<MarginRight>0.50in</MarginRight>" &
"<MarginBottom>0.25in</MarginBottom>" &
"</DeviceInfo>"
Dim warnings As Warning()
m_streams = New List(Of Stream)()
report.Render("Image", deviceInfo, AddressOf CreateStream, warnings)
For Each stream As Stream In m_streams
stream.Position = 0
Next
End Sub
' Handler for PrintPageEvents
Private Sub PrintPage(ByVal sender As Object, ByVal ev As PrintPageEventArgs)
Dim pageImage As New Metafile(m_streams(m_currentPageIndex))
' Adjust rectangular area with printer margins.
Dim adjustedRect As New Rectangle(ev.PageBounds.Left - CInt(ev.PageSettings.HardMarginX),
ev.PageBounds.Top - CInt(ev.PageSettings.HardMarginY),
ev.PageBounds.Width,
ev.PageBounds.Height)
' Draw a white background for the report
ev.Graphics.FillRectangle(Brushes.White, adjustedRect)
' Draw the report content
ev.Graphics.DrawImage(pageImage, adjustedRect)
' Prepare for the next page. Make sure we haven't hit the end.
m_currentPageIndex += 1
ev.HasMorePages = (m_currentPageIndex < m_streams.Count)
End Sub
Private Sub PrintRep()
If m_streams Is Nothing OrElse m_streams.Count = 0 Then
Throw New Exception("Error: no stream to print.")
End If
Dim printDoc As New PrintDocument()
If Not printDoc.PrinterSettings.IsValid Then
**
It FAILS HERE!!!!
**
Throw New Exception("Error: cannot find the printer.")
Else
AddHandler printDoc.PrintPage, AddressOf PrintPage
m_currentPageIndex = 0
printDoc.Print()
End If
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
If m_streams IsNot Nothing Then
For Each stream As Stream In m_streams
stream.Close()
Next
m_streams = Nothing
End If
End Sub
Private Function LoadSuperFinalChkVwData(AssySN As String) As DataTable
Dim sqlConnection1 As New SqlConnection("Data Source=AOXWEBAPP1\SQLEXPRESS;Initial Catalog=ManufacturingApps;User ID=AppUser;Password=#ppus3r;ApplicationIntent=ReadWrite")
Dim querystring As String = "SELECT * FROM dbo.Super_FinalChkVw WHERE AssySN = '" & AssySN & "'"
Dim adapter As New SqlDataAdapter(querystring, sqlConnection1)
Dim superfinalchkvw As New DataSet("DataSet1")
adapter.Fill(superfinalchkvw, "Super_FinalChkVw")
Return superfinalchkvw.Tables(0)
End Function
Protected Sub Print_Click(sender As Object, e As EventArgs) Handles Print.Click
Dim report As New LocalReport()
Dim sqlConnection2 As New SqlConnection("Data Source=AOXWEBAPP1\SQLEXPRESS;Initial Catalog=ManufacturingApps;User ID=AppUser;Password=#ppus3r;ApplicationIntent=ReadWrite")
Dim cmd2 As New SqlCommand
Dim cudate As DateTime
Dim AssySN As String
Dim cntr As Integer = 0
Dim SelectCount As Integer = 0
cudate = DateTime.Now
cmd2.Parameters.AddWithValue("#cudate", cudate)
For Each row As GridViewRow In PrintATRs.Rows
cntr = cntr + 1
Dim cb As CheckBox = DirectCast(row.FindControl("checkbox3"), CheckBox)
AssySN = row.Cells(3).Text
If cb.Checked Then
SelectCount = SelectCount + 1
report.ReportPath = "..\..\Manufacture\Superiox\ATR.rdlc"
report.DataSources.Clear()
report.DataSources.Add(New ReportDataSource("DataSet1", LoadSuperFinalChkVwData(AssySN)))
Export(report)
PrintRep()
cmd2.CommandText = "UpDate Super_FinalChk SET Selected=0, Printed=1, PrintDate=#cudate WHERE AssySN = '" & AssySN & "';"
cmd2.Connection = sqlConnection2
sqlConnection2.Open()
cmd2.ExecuteNonQuery()
sqlConnection2.Close()
End If
Next
Dim adapter As New SqlDataAdapter(GridViewQry, sqlConnection2)
Dim superfinalchk As New DataSet("SqlDataSource1")
adapter.Fill(superfinalchk, "Super_FinalChkVw")
PrintATRs.DataSource = superfinalchk
PrintATRs.DataBind()
If SelectCount > 0 Then
TextBox1.Text = "Reports Have Been Printed!"
Else
TextBox1.Text = "Please Select Reports to Print!"
End If
End Sub

vb.net using ashx handler to get image from SQL Server

I have employee images stored in my EMPPhotos table on SQL Server 2008 R2 in an image datatype. I created a generic handler to get the image from the table and send it to the page. It does not work. I have tested the query itself and I am getting data.
The handler:
<%# WebHandler Language="VB" Class="EmpImageHandler" %>
Imports System
Imports System.Web
Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.IO
Imports System.Data
Imports System.Data.SqlClient
Public Class EmpImageHandler : Implements IHttpHandler
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
'context.Response.ContentType = "text/bmp"
'context.Response.Write("Hello World")
context.Response.ContentType = "text/bmp"
Dim img As Image = GetImage(context.Request.QueryString("id"))
img.Save(context.Response.OutputStream, ImageFormat.Bmp)
End Sub
Private Function GetImage(inID As Long) As Image
Dim ms As MemoryStream = New MemoryStream
Dim cnSTR As New clsConnections
Dim cn As New SqlConnection(cnSTR.ConnectToDB("AgencyStaff"))
Try
cn.Open()
Catch ex As Exception
End Try
Dim ssql As String = "Select BMPPhoto From EMPPhotos where empid = " & inID
Dim CMD As SqlCommand = New SqlCommand(ssql, cn)
Dim dr As SqlDataReader = CMD.ExecuteReader
dr.Read()
Dim img() As Byte = CType(dr("BMPPhoto"), Byte())
ms = New MemoryStream(img, False)
Return Image.FromStream(ms)
End Function
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return True
End Get
End Property
End Class
Thanks in advance for your assistance.
Change your ContentType.
From:
context.Response.ContentType = "text/bmp"
To:
context.Response.ContentType = "image/bmp"

Access sessions in asp.net handler

I am trying to upload images using generic handler as shown below and I have a normal aspx page where I am showing all the uploaded images after uploading.Everything is working fine.
<%# WebHandler Language="VB" Class="Upload"%>
Imports System
Imports System.Web
Imports System.Threading
Imports System.Web.Script.Serialization
Imports System.IO
Public Class Upload : Implements IHttpHandler, System.Web.SessionState.IRequiresSessionState
Public Class FilesStatus
Public Property thumbnail_url() As String
Public Property name() As String
Public Property url() As String
Public Property size() As Integer
Public Property type() As String
Public Property delete_url() As String
Public Property delete_type() As String
Public Property [error]() As String
Public Property progress() As String
End Class
Private ReadOnly js As New JavaScriptSerializer()
Private ingestPath As String
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim r = context.Response
ingestPath = context.Server.MapPath("~/UploadedImages/")
r.AddHeader("Pragma", "no-cache")
r.AddHeader("Cache-Control", "private, no-cache")
HandleMethod(context)
End Sub
Private Sub HandleMethod(ByVal context As HttpContext)
Select Case context.Request.HttpMethod
Case "HEAD", "GET"
ServeFile(context)
Case "POST"
UploadFile(context)
Case "DELETE"
DeleteFile(context)
Case Else
context.Response.ClearHeaders()
context.Response.StatusCode = 405
End Select
End Sub
Private Sub DeleteFile(ByVal context As HttpContext)
Dim filePath = ingestPath & context.Request("f")
If File.Exists(filePath) Then
File.Delete(filePath)
End If
End Sub
Private Sub ServeFile(ByVal context As HttpContext)
If String.IsNullOrEmpty(context.Request("f")) Then
ListCurrentFiles(context)
Else
DeliverFile(context)
End If
End Sub
Private Sub UploadFile(ByVal context As HttpContext)
Dim statuses = New List(Of FilesStatus)()
Dim headers = context.Request.Headers
If String.IsNullOrEmpty(headers("X-File-Name")) Then
UploadWholeFile(context, statuses)
Else
UploadPartialFile(headers("X-File-Name"), context, statuses)
End If
WriteJsonIframeSafe(context, statuses)
End Sub
Private Sub UploadPartialFile(ByVal fileName As String, ByVal context As HttpContext, ByVal statuses As List(Of FilesStatus))
If context.Request.Files.Count <> 1 Then
Throw New HttpRequestValidationException("Attempt to upload chunked file containing more than one fragment per request")
End If
Dim inputStream = context.Request.Files(0).InputStream
Dim fullName = ingestPath & Path.GetFileName(fileName)
Using fs = New FileStream(fullName, FileMode.Append, FileAccess.Write)
Dim buffer = New Byte(1023) {}
Dim l = inputStream.Read(buffer, 0, 1024)
Do While l > 0
fs.Write(buffer, 0, l)
l = inputStream.Read(buffer, 0, 1024)
Loop
fs.Flush()
fs.Close()
End Using
statuses.Add(New FilesStatus With {.thumbnail_url = "Thumbnail.ashx?f=" & fileName, .url = "Upload.ashx?f=" & fileName, .name = fileName, .size = CInt((New FileInfo(fullName)).Length), .type = "image/png", .delete_url = "Upload.ashx?f=" & fileName, .delete_type = "DELETE", .progress = "1.0"})
End Sub
Private Sub UploadWholeFile(ByVal context As HttpContext, ByVal statuses As List(Of FilesStatus))
For i As Integer = 0 To context.Request.Files.Count - 1
Dim file = context.Request.Files(i)
file.SaveAs(ingestPath & Path.GetFileName(file.FileName))
Thread.Sleep(1000)
Dim fname = Path.GetFileName(file.FileName)
statuses.Add(New FilesStatus With {.thumbnail_url = "Thumbnail.ashx?f=" & fname, .url = "Upload.ashx?f=" & fname, .name = fname, .size = file.ContentLength, .type = "image/png", .delete_url = "Upload.ashx?f=" & fname, .delete_type = "DELETE", .progress = "1.0"})
Next i
End Sub
Private Sub WriteJsonIframeSafe(ByVal context As HttpContext, ByVal statuses As List(Of FilesStatus))
context.Response.AddHeader("Vary", "Accept")
Try
If context.Request("HTTP_ACCEPT").Contains("application/json") Then
context.Response.ContentType = "application/json"
Else
context.Response.ContentType = "text/plain"
End If
Catch
context.Response.ContentType = "text/plain"
End Try
Dim jsonObj = js.Serialize(statuses.ToArray())
context.Response.Write(jsonObj)
End Sub
Private Sub DeliverFile(ByVal context As HttpContext)
Dim filePath = ingestPath & context.Request("f")
If File.Exists(filePath) Then
context.Response.ContentType = "application/octet-stream"
context.Response.WriteFile(filePath)
context.Response.AddHeader("Content-Disposition", "attachment, filename=""" & context.Request("f") & """")
Else
context.Response.StatusCode = 404
End If
End Sub
Private Sub ListCurrentFiles(ByVal context As HttpContext)
Dim files = New List(Of FilesStatus)()
Dim names = Directory.GetFiles(context.Server.MapPath("~/UploadedImages/"), "*", SearchOption.TopDirectoryOnly)
For Each name In names
Dim f = New FileInfo(name)
files.Add(New FilesStatus With {.thumbnail_url = "Thumbnail.ashx?f=" & f.Name, .url = "Upload.ashx?f=" & f.Name, .name = f.Name, .size = CInt(f.Length), .type = "image/png", .delete_url = "Upload.ashx?f=" & f.Name, .delete_type = "DELETE"})
Next name
context.Response.AddHeader("Content-Disposition", "inline, filename=""files.json""")
Dim jsonObj = js.Serialize(files.ToArray())
context.Response.Write(jsonObj)
context.Response.ContentType = "application/json"
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
Now I want to add a session variable by generating a random string and add the uploaded images to the newly created random string.
1.I have seen this Question on SO to use System.Web.SessionState.IRequiresSessionState for sessions and how do I create a folder with that and add my images to that folder after doing that how do I access this session variable in my normal aspx page.
2.(Or) the better way is create session variable in aspx page and pass that to handler?If so how can I do that?
3 .I am trying to find the control from my handler.Is that possible?If anyone knows how to get this then also my problem will get resolved so that I am trying to create a session from m aspx page.
Can anyone explain the better way of handling this situation.
I completely agree with jbl's comment.
You can get and set session using HttpContext.Current.Session anywhere on your project.
No matter where you create the session. Just make sure that the session exists before you access it.
Not sure what exactly you are asking here(need some more explanation).
Here is an example, where I used session on HttpHandler. However, it is on c#(hope you can understand).
This is not really an answer but #Knvn wrote a C# example which I couldn't understand so I used a converter to convert it to VB. Posted it here in case it helps someone in the future.
Public Class HttpHandler
Implements IHttpHandler
Implements IRequiresSessionState
Public Sub New()
End Sub
Public Sub ProcessRequest(context As HttpContext)
Dim Request As HttpRequest = context.Request
Dim Response As HttpResponse = context.Response
If SessionHandler.Current.UserID = 0 Then
Response.Redirect("~/Default.aspx")
Else
Try
If Request.Path.EndsWith(".pdf") Then
Dim client As New WebClient()
Dim buffer As [Byte]() = client.DownloadData(HttpContext.Current.Server.MapPath(Request.Path))
Response.ContentType = "application/pdf"
Response.AddHeader("content-length", buffer.Length.ToString())
Response.BinaryWrite(buffer)
Else
Using reader As New StreamReader(HttpContext.Current.Server.MapPath(Request.Path))
Response.Write(reader.ReadToEnd())
End Using
End If
Catch
Response.Redirect("~/Default.aspx")
End Try
End If
End Sub
Public ReadOnly Property IsReusable() As Boolean
' To enable pooling, return true here.
' This keeps the handler in memory.
Get
Return False
End Get
End Property
End Class

Upload Image in ASP.NET VB

Is there any way an image can be uploaded with ASP.NET with VB?
I need an "upload" button on the ASP.NET side.
I already have an image field in the table in SQL server 2008.
Is there any way I can do this?
Add a fileupload control with:
<asp:FileUpload runat="server" id="FileUpload1" />
Add an upload button, and place this in the button click event handler:
Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim bldgIDNum As Int32 = FormView_Building.SelectedValue
If FileUpload1.PostedFile IsNot Nothing AndAlso FileUpload1.PostedFile.FileName <> "" Then
Dim imageSize As Byte() = New Byte(FileUpload1.PostedFile.ContentLength - 1) {}
Dim uploadedImage__1 As HttpPostedFile = FileUpload1.PostedFile
uploadedImage__1.InputStream.Read(imageSize, 0, CInt(FileUpload1.PostedFile.ContentLength))
' Create SQL Connection
Dim con As New SqlConnection()
con.ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
' Create SQL Command
Dim cmd As New SqlCommand()
cmd.CommandText = "INSERT INTO Table (PrimaryKey,ImageData) VALUES (#PrimaryKey,#ImageData)"
cmd.CommandType = CommandType.Text
cmd.Connection = con
Dim PrimaryKey As New SqlParameter("#PrimaryKey", SqlDbType.Int, 32)
PrimaryKey.Value = (however you want to get it)
Dim UploadedImage__2 As New SqlParameter("#ImageData", SqlDbType.Image, imageSize.Length)
UploadedImage__2.Value = imageSize
cmd.Parameters.Add(UploadedImage__2)
con.Open()
Dim result As Integer = cmd.ExecuteNonQuery()
con.Close()
If result > 0 Then
lblMessage.Text = "File Uploaded"
End If
End If
ListView_BldgImages.DataBind()
End Sub
The database column ImageData should be varbinary(max)
Create a handler called Handler_Image.ashx with the following content:
Imports System
Imports System.Web
Imports System.Configuration
Imports System.Data.SqlClient
Public Class Handler_Image : Implements IHttpHandler
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim con As New SqlConnection()
con.ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
' Create SQL Command
Dim cmd As New SqlCommand()
cmd.CommandText = "Select ImageData from Table where PrimaryKey =#PrimaryKey"
cmd.CommandType = System.Data.CommandType.Text
cmd.Connection = con
Dim ID As New SqlParameter("#PrimaryKey", System.Data.SqlDbType.Int)
ID.Value = context.Request.QueryString("PrimaryKey")
cmd.Parameters.Add(ID)
con.Open()
Dim dReader As SqlDataReader = cmd.ExecuteReader()
dReader.Read()
context.Response.BinaryWrite(DirectCast(dReader("ImageData"), Byte()))
dReader.Close()
con.Close()
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
Display the image with an image control with the following property:
ImageUrl='<%# "Handler_Image.ashx?PrimaryKey=" & Eval("PrimaryKey")%>'
Replace the connectionstring, the table name, and the primary key to suit your application

Resources