Resizing an image in asp.net VB.net - asp.net

In the application I am working on I need to resize a picture and add it to the database I have implemented something to do so but I have a problem saving the resulting BMP file in the memory stream so that my implementation works with the existing code.Also the source from my image comes from a variable called fu (File upload object) I was also wondering if the way to access the source of the file is to use fu.name or fu.Filecontents. Also I have Enclosed what I implemented in beginning of my implementation and Ending of my implementation as the other code was done by a colleague who is not with me anymore.
Here is the code:
Public Function UploadFile(fu As FileUpload, expID As Integer) As Integer
GetConnectionString()
Dim con As New SqlConnection(connString.ConnectionString)
Dim dataAdapter As New SqlDataAdapter
Dim myCommandBuilder As SqlCommandBuilder
Dim dataSet As New DataSet
Dim memoryStream As MemoryStream
Dim bData As Byte()
Dim reader As BinaryReader
Dim expense As New Expense(expID)
Dim loggedInUser As New Employee(Membership.GetUser.UserName)
Try
UploadFile = 1
'check that the logged in user has the right to attach a file to the current expense
If loggedInUser.ID = expense.Rpt.Emp.ID Or loggedInUser.ID = expense.Rpt.Emp.Supervisor Or loggedInUser.ID = expense.Rpt.Emp.Finalizer Or loggedInUser.ID = expense.Rpt.Emp.DelegatedTo Then
If fu.HasFile Then
If fu.FileContent.Length < 5000000 Then
dataAdapter = New SqlDataAdapter("SELECT * FROM tblExpense WHERE EXPENSE_ID=" & expID, con)
myCommandBuilder = New SqlCommandBuilder(dataAdapter)
dataAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey
con.Open()
dataAdapter.Fill(dataSet, "tblExpense")
'Begining of my implementation
' Get the scale factor.
Dim scale_factor As Single = Single.Parse(0.33)
' Get the source bitmap.
Dim bm_source As New Bitmap(fu.FileContent)
' Make a bitmap for the result.
Dim bm_dest As New Bitmap(
CInt(bm_source.Width * scale_factor),
CInt(bm_source.Height * scale_factor))
' Make a Graphics object for the result Bitmap.
Dim gr_dest As Graphics = Graphics.FromImage(bm_dest)
' Copy the source image into the destination bitmap.
gr_dest.DrawImage(bm_source, 0, 0,
bm_dest.Width + 1,
bm_dest.Height + 1)
'Ending of my implementation
reader = New BinaryReader(fu.FileContent)
bData = reader.ReadBytes(reader.BaseStream.Length)
memoryStream = New MemoryStream(bData, 0, bData.Length)
memoryStream.Close()
dataSet.Tables("tblExpense").Rows(0)("RECEIPT") = bData
Select Case UCase(Right(fu.PostedFile.FileName, 3))
Case "JPG" : dataSet.Tables("tblExpense").Rows(0)("RECEIPT_TYPE") = "image/jpeg"
Case "PNG" : dataSet.Tables("tblExpense").Rows(0)("RECEIPT_TYPE") = "image/png"
Case "GIF" : dataSet.Tables("tblExpense").Rows(0)("RECEIPT_TYPE") = "image/gif"
Case "PDF" : dataSet.Tables("tblExpense").Rows(0)("RECEIPT_TYPE") = "application/pdf"
Case "TXT" : dataSet.Tables("tblExpense").Rows(0)("RECEIPT_TYPE") = "text/plain"
Case "HTM" : dataSet.Tables("tblExpense").Rows(0)("RECEIPT_TYPE") = "text/html"
Case "HTML" : dataSet.Tables("tblExpense").Rows(0)("RECEIPT_TYPE") = "text/html"
Case Else : dataSet.Tables("tblExpense").Rows(0)("RECEIPT_TYPE") = "image/jpeg"
End Select
dataSet.Tables("tblExpense").Rows(0)("RECEIPT_NAME") = expense.Rpt.Emp.EmpNum & "-" & expense.Rpt.Name & "-" & expense.ID
dataSet.Tables("tblExpense").Rows(0)("RECEIPT_DATE") = Now
dataAdapter.Update(dataSet, "tblExpense")
Else
UploadFile = 2

Related

Emails' rich characters are mistranslated when read from database using MimeKit

I have a windows service written in VB.Net that downloads emails into MimeMessage objects, removes their attachments, and then writes the remains of the email to a SQL Server database. A separate ASP.Net application (using VB.Net) reads the email back into a MimeMessage object and returns it to the user upon request.
Something happens during this process that causes strange characters to appear in the output.
This question (Content encoding using MimeKit/MailKit) seemed promising, but changing the character encoding from ASCII to UTF8 etc didn't solve it.
Here’s the code that saves the email to the database:
Sub ImportEmail(exConnectionString As String)
Dim oClient As New Pop3Client()
' … email connection code removed …
Dim message = oClient.GetMessage(0)
Dim strippedMessage As MimeMessage = message
' … code to remove attachments removed …
Dim mem As New MemoryStream
strippedMessage.WriteTo(mem)
Dim bytes = mem.ToArray
Dim con As New SqlConnection(exConnectionString)
con.Open()
Dim com As New SqlCommand("INSERT INTO Emails (Body) VALUES (#RawDocument)", con)
com.CommandType = CommandType.Text
com.Parameters.AddWithValue("#RawDocument", bytes)
com.ExecuteNonQuery()
con.Close()
End Sub
And here’s the ASP.Net code to read it back to the user:
Private Sub OutputEmail(exConnectionString As String)
Dim BlobString As String = ""
Dim Sql As String = "SELECT Body FROM Emails WHERE Id = #id"
Dim com As New SqlClient.SqlCommand(Sql)
com.CommandType = CommandType.Text
com.Parameters.AddWithValue("#id", ViewState("email_id"))
Dim con As New SqlConnection(exConnectionString)
con.Open()
com.Connection = con
Dim da As New SqlClient.SqlDataAdapter(com)
Dim dt As New DataTable()
da.Fill(dt)
con.Close()
If dt.Rows.Count > 0 Then
Dim Row = dt.Rows(0)
BlobString = Row(0).ToString()
Dim MemStream As MemoryStream = GetMemoryStreamFromASCIIEncodedString(BlobString)
Dim message As MimeMessage = MimeMessage.Load(MemStream)
BodyBuilder.HtmlBody = message.HtmlBody
BodyBuilder.TextBody = message.TextBody
message.Body = BodyBuilder.ToMessageBody()
Response.ContentType = "message/rfc822"
Response.AddHeader("Content-Disposition", "attachment;filename=""" & Left(message.Subject, 35) & ".eml""")
Response.Write(message)
Response.End()
End If
End Sub
Private Function GetMemoryStreamFromASCIIEncodedString(ByVal BlobString As String) As MemoryStream
Dim BlobStream As Byte() = Encoding.ASCII.GetBytes(BlobString) ' **
Dim MemStream As MemoryStream = New MemoryStream()
MemStream.Write(BlobStream, 0, BlobStream.Length)
MemStream.Position = 0
Return MemStream
End Function
For example, let’s say the text below appears in the original email:
“So long and thanks for all the fish” (fancy quotes)
When read back, it appears as follows:
†So long and thanks for all the fishâ€
Other character replacements are as follows:
– (long dash) becomes –
• (bullets) become •
The problem is with the following snippet:
If dt.Rows.Count > 0 Then
Dim Row = dt.Rows(0)
BlobString = Row(0).ToString() ' <-- the ToString() is the problem
Dim MemStream As MemoryStream = GetMemoryStreamFromASCIIEncodedString(BlobString)
Dim message As MimeMessage = MimeMessage.Load(MemStream)
To fix the data corruption, what you need to do is this:
If dt.Rows.Count > 0 Then
Dim Row = dt.Rows(0)
Dim BlobString as Byte() = Row(0)
Dim MemStream As MemoryStream = new MemoryStream (BlobString, False)
Dim message As MimeMessage = MimeMessage.Load(MemStream)
You can also get rid of your GetMemoryStreamFromASCIIEncodedString function.
(Note: I don't know VB.NET, so I'm just guessing at the syntax, but it should be pretty close to being right)

Can't retrive image from mdb database this program show error "parameter in not valid"

Try
'connection string
Dim dbpath As String = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase)
dbpath = New Uri(dbpath).LocalPath
Dim my_connection As String = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=D:\DataBase\KhandagramPS.mdb"
Dim userTables As DataTable = Nothing
Dim connection As System.Data.OleDb.OleDbConnection = New System.Data.OleDb.OleDbConnection()
Dim DR As OleDbDataReader
'Dim source As String
'query string
Dim my_query As String = "SELECT sl_no,f_name,dob,sex,add,reg,[class],a_date,a_per,r_a_per,f_status,[name],photo,document FROM " & TextBox2.Text & " where sl_no=" & TextBox3.Text & " ;"
'create a connection
Dim my_dbConnection As New OleDbConnection(my_connection)
my_dbConnection.Open()
'create a command
Dim my_Command As New OleDbCommand(my_query, my_dbConnection)
DR = my_Command.ExecuteReader()
While (DR.Read())
txtslno.Text = (DR(0).ToString())
txtfname.Text = (DR(1).ToString())
Date1.Text = (DR(2).ToString())
comsex.Text = (DR(3).ToString())
txtadd.Text = (DR(4).ToString())
txtreg.Text = (DR(5).ToString())
comclass.Text = (DR(6).ToString())
Date2.Text = (DR(7).ToString())
txtaper.Text = (DR(8).ToString())
txtraper.Text = (DR(9).ToString())
txtfstatus.Text = (DR(10).ToString())
txtname.Text = (DR(11).ToString())
Dim ImageBuffer = CType(DR(12), Byte())
Dim imgStrm As New MemoryStream(ImageBuffer, True)
imgStrm.Write(ImageBuffer, 0, ImageBuffer.Length)
Dim img As Image = Image.FromStream(imgStrm)
PictureBox1.Image = img
End While
'close connection
my_dbConnection.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
I suspect some error in your Byte-Array to Image conversion. Make sure that your Byte-Array is not messed up. Use this function instead.
Private Function getImage(imageBuffer as Byte())
Using ms as new IO.MemoryStream(imageBuffer)
Dim img = ImageIO.FromStream(ms)
Return img
End Using
End Function
my 2 cents: you shouldn't store images in an mdb file (unless things have changed a lot in the past few years). store images in a separate directory and store the file paths in the mdb so the image can be found when needed.

itextsharp SetFields not setting

I have my temp PDF on the network and am using asp to fill in the fields and then download the file.
The problem I have is that the file downloaded is just the blank template, none of the fields are filled?
My code
Dim doc As New Document(PageSize.A4.Rotate)
Dim ms As New MemoryStream()
Dim writer = PdfWriter.GetInstance(doc, ms)
writer.Open()
Dim PdfR As New PdfReader("http://192.168.0.221/template.pdf")
Dim PdfS As New PdfStamper(PdfR, ms)
Dim fields As AcroFields = PdfS.AcroFields
fields.SetField("s1", "00")
fields.SetField("pono", "100")
PdfS.FormFlattening = True
PdfS.Close()
PdfR.Close()
Dim r = System.Web.HttpContext.Current.Response
r.ContentType = "application/pdf"
r.AddHeader("Content-Disposition", String.Format("attachment;filename=Testing.pdf", "Testing"))
r.BinaryWrite(ms.ToArray)
If anyone else ever hits this issue
1) If you dont mind your fields being editable then remove the FormFlattening command
2) Else add this fields.GenerateAppearances = True

Convert WebControl Image to iText.text.image

This is my code
Dim doc As iTextSharp.text.Document = New iTextSharp.text.Document()
Dim path As String = Request.MapPath("Sample PDFs") & "\Sample.tif"
PdfWriter.GetInstance(doc, New FileStream(Request.PhysicalApplicationPath + _
"render\1.pdf", FileMode.Create))
Dim data As clsData = New clsData(GetConnection, enumEgswFetchType.DataTable)
Dim int As Integer = data.GetPageCount(path)
doc.Open()
For ctr As Integer = 0 To int - 1
Dim img As iTextSharp.text.Image
Dim image As New System.Web.UI.WebControls.Image
image.ImageUrl = "ctrls/ViewTif.aspx?path=" + path.ToString + "&page=" + ctr.ToString
img = iTextSharp.text.Image.GetInstance(image, System.Web.UI.WebControls.Image)
doc.Add(image)
Next
doc.Close()
Response.Redirect("~/1.pdf")
Is there any way that I can get the webcontrol image to the itext? the image variable is a dynamic image with a source page returning a jpeg image from a tif file. Or is there any way I can directly put the tif to itext as pdf?
Is there a reason that you need to use System.Web.UI.WebControls.Image? One of the overloads for iTextSharp.text.Image.GetInstance() accepts a URL:
Dim TestFile = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Test.pdf")
Using FS As New FileStream(TestFile, FileMode.Create, FileAccess.Write, FileShare.None)
Using Doc As New Document()
Using Writer = PdfWriter.GetInstance(Doc, FS)
Doc.Open()
Doc.Add(New Paragraph("Hello World"))
''//Get the image from a URL
Dim Img = iTextSharp.text.Image.GetInstance("http://www.google.com/images/srpr/logo4w.png")
''//Optionally adjust it
Img.ScaleAbsolute(100, 200)
''//Add it to the document
Doc.Add(Img)
Doc.Close()
End Using
End Using
End Using

InvalidCastException when reading a BLOB object (PDF File) from an SQL Database

I'm having problems with an Invalid Cast Exception when I try and read a PDF from a database as a BLOB. I am able to write the files into the database no problems at all, however, when I try to retrieve them I just get InvalidCastException.
Here is the code I'm using:
Protected Sub btnPDF_Click(sender As Object, e As EventArgs) Handles btnPDF.Click
' Request.QueryString["docid"].ToString();
Dim docuid As String = "b39a443d-ccfd-47f4-b333-f12cd94683d6"
'Connection and Parameters
Dim param As SqlParameter = Nothing
Dim conn As SqlConnection = New SqlConnection(
ConfigurationManager.ConnectionStrings("menu").ToString())
Dim cmd As New SqlCommand("sp_getdoc", conn)
cmd.CommandType = CommandType.StoredProcedure
param = New SqlParameter("#docuid", SqlDbType.NVarChar, 100)
param.Direction = ParameterDirection.Input
param.Value = docuid
cmd.Parameters.Add(param)
'Open connection and fetch the data with reader
conn.Open()
Dim reader As SqlDataReader =
cmd.ExecuteReader(CommandBehavior.CloseConnection)
If reader.HasRows Then
reader.Read()
'
Dim doctype As String = reader("doctype").ToString()
Dim docname As String = reader("docname").ToString()
'
Response.Buffer = False
Response.ClearHeaders()
Response.ContentType = doctype
Response.AddHeader("Content-Disposition",
"attachment; filename=" + docname)
'
'Code for streaming the object while writing
Const ChunkSize As Integer = 1024
Dim buffer() As Byte = New Byte(ChunkSize) {}
Dim binary(reader("document")) As Byte
Dim ms As New MemoryStream(binary)
Dim SizeToWrite As Integer = ChunkSize
For i As Integer = 0 To binary.GetUpperBound(0) - 1 Step i = i + ChunkSize
If Not Response.IsClientConnected Then
Return
End If
If i + ChunkSize >= binary.Length Then
SizeToWrite = binary.Length - i
End If
Dim chunk(SizeToWrite) As Byte
ms.Read(chunk, 0, SizeToWrite)
Response.BinaryWrite(chunk)
Response.Flush()
Next
Response.Close()
End If
End Sub
I am encountering the problem specifically on the following line:
Dim binary(reader("document")) As Byte
It seems to think that binary is being passed an Integer. Is this something to do with the SQLReader? I'm not really sure at this point what the problem is.
Any help would be greatly appreciated.
Many Thanks,
Richard E Logan-Baker
*UPDATE*
I have since worked out the problem that I'm getting by changing the lines to:
Dim blob() As Byte
blob = reader.Item("document")
However, the PDF does not display inside firefox, and when I save the file (even though my DB is only 2MB~) it is quite happy at downloading over 40MB of data! Also, the file size reports as unknown. I am really stuck now.
*UPDATE*
I've now got the PDF to open in the browser, but there is no data being displayed and Adobe Acrobat says it has problems extracting the text/fonts from the file and that the PDF is broken somehow.
Here is my updated code now:
Protected Sub btnPDF_Click(sender As Object, e As EventArgs) Handles btnPDF.Click
' Request.QueryString["docid"].ToString();
Dim docuid As String = "ba32bf45-1b5c-451a-969c-290dc2cf9073"
'Connection and Parameters
Dim param As SqlParameter = Nothing
Dim conn As SqlConnection = New SqlConnection(
ConfigurationManager.ConnectionStrings("menu").ToString())
Dim cmd As New SqlCommand("sp_getdoc", conn)
cmd.CommandType = CommandType.StoredProcedure
param = New SqlParameter("#docuid", SqlDbType.NVarChar, 100)
param.Direction = ParameterDirection.Input
param.Value = docuid
cmd.Parameters.Add(param)
'Open connection and fetch the data with reader
conn.Open()
Dim reader As SqlDataReader =
cmd.ExecuteReader(CommandBehavior.CloseConnection)
If reader.HasRows Then
reader.Read()
'
Dim doctype As String = reader("doctype").ToString()
Dim docname As String = reader("docname").ToString()
'
Response.Buffer = False
Response.ClearHeaders()
Response.ContentType = doctype
Response.AddHeader("Content-Disposition",
"attachment; filename=" + docname)
'
'Code for streaming the object while writing
Const ChunkSize As Integer = 1024
Dim buffer() As Byte = New Byte(ChunkSize) {}
Dim blob() As Byte
blob = reader.Item("document")
Dim ms As New MemoryStream(blob)
Dim SizeToWrite As Integer = ChunkSize
For i As Integer = 0 To blob.GetUpperBound(0) - 1
If Not Response.IsClientConnected Then
Return
End If
If i + ChunkSize >= blob.Length Then
SizeToWrite = blob.Length - i
End If
Dim chunk(SizeToWrite) As Byte
ms.Read(chunk, 0, SizeToWrite)
Response.BinaryWrite(chunk)
Response.Flush()
i = i + ChunkSize
Next i
Response.Close()
End If
End Sub
I think your problem is coming from the way you are incrementing "i" inside the loop. After you increment it by the ChunkSize at the end of your For...Next statement, the "Next i" statement will increment it by 1 again. Try changing that line to:
i = i + ChunkSize - 1
Or alternatively you could add a "Step ChunkSize" at the end of the For statement and remove the line I'm referring to.

Resources