I am trying to attach a binary data retrieved from MySQL server to an email as attachment using VB.net.
I can send out a email with attachment but not able to open any of the attachment file even word file also is empty.
The error message is --> Adobe Reader could not open "xxx.pdf" because it is either not a supported file type or because the file has been damaged (for example, it was sent as an email attachment and wasn't correctly decoded).
Been googled around but still not able to find out what is wrong with my code.
Anyone can help will be very appreciated!Thanks!
Dim m_ImageBinary As [Byte]() = New [Byte](-1) {}
Dim m_AttachmentType As String = ""
Dim m_AttachmentName As String = ""
Dim m_Attachment As Boolean = False
Dim cmd3 As New MySqlCommand("SELECT Attachment, AttachmentType, AttachmentName FROM tbcommunication WHERE CommunicationID = " & cid, MySql)
Dim rdr2 As MySqlDataReader = cmd3.ExecuteReader()
While rdr2.Read()
If rdr2("Attachment").ToString() <> "" Then
Dim m_Length As Integer = DirectCast(rdr2("Attachment"), [Byte]()).Length
m_ImageBinary = New [Byte](m_Length - 1) {}
m_ImageBinary = DirectCast(rdr2("Attachment"), [Byte]())
m_AttachmentType = rdr2("AttachmentType").ToString()
m_AttachmentName = rdr2("AttachmentName").ToString()
End If
End While
If m_ImageBinary.Length <> 0 Then
If m_Attachment = False Then
If m_AttachmentType.Contains("jpeg") OrElse m_AttachmentType.Contains("bmp") OrElse m_AttachmentType.Contains("gif") Then
m_Attachment = False
Else
m_Attachment = True
End If
End If
If m_Attachment = True Then
' If not image file
Response.AppendHeader("content-disposition", "attachment; filename=" & m_Atta`enter code here`chmentName)
End If
'Write(binary)
'Response.ContentType = m_AttachmentType
'Response.BinaryWrite(m_ImageBinary)
'Response.[End]()
End If
Dim mailmssg As New MailMessage()
Dim smtp_client As New SmtpClient
Using memoryStream As New MemoryStream()
Dim bytes As Byte() = memoryStream.ToArray()
Dim att As New Attachment(New MemoryStream(bytes), m_AttachmentName)
mailmssg.Attachments.Add(att)
MemoryStream.Dispose()
smtp_client.DeliveryMethod = SmtpDeliveryMethod.Network
smtp_client.Send(mailmssg)
End Using
'...
' memoryStream = new blank MemoryStream
Using memoryStream As New MemoryStream()
' get emtpy array from memoryStream
Dim bytes As Byte() = memoryStream.ToArray()
' Create empty MemoryStream from empty bytes array
Dim att As New Attachment(New MemoryStream(bytes), m_AttachmentName)
'...
With your current code you'll never send anything than an empty file with a name and always only one.
Related
I have the following JSON response:
{
"status": "Success",
"label": "pdf_base64_string",
"order": "ABC123456"
}
I'm trying to save a PDF file from the Base64 string per the following code:
FileData = Base64DecodeString(pdf_base64_string)
fileNum = FreeFile
FilePath = "C:\label.pdf"
Open FilePath For Binary Access Write As #fileNum
Put #fileNum, 1, FileData
Close #fileNum
This results in a broken/invalid PDF file (not recognized by the PDF viewer).
Adapted from: Inserting an Image into a sheet using Base64 in VBA?
This works for me - saves the file to the same location as the workbook running the code.
Sub TestDecodeToFile()
Dim strTempPath As String
Dim b64test As String
'little face logo
b64test = "R0lGODlhDwAPAKECAAAAzMzM/////wAAACwAAAAADwAPAAACIISPeQHsrZ5ModrLlN48" & _
"CXF8m2iQ3YmmKqVlRtW4MLwWACH+H09wdGltaXplZCBieSBVbGVhZCBTbWFydFNhdmVyIQAAOw=="
strTempPath = ThisWorkbook.Path & "\temp.png" 'use workbook path as temp path
'save byte array to temp file
Open strTempPath For Binary As #1
Put #1, 1, DecodeBase64(b64test)
Close #1
End Sub
Private Function DecodeBase64(ByVal strData As String) As Byte()
Dim objXML As Object 'MSXML2.DOMDocument
Dim objNode As Object 'MSXML2.IXMLDOMElement
'get dom document
Set objXML = CreateObject("MSXML2.DOMDocument")
'create node with type of base 64 and decode
Set objNode = objXML.createElement("b64")
objNode.DataType = "bin.base64"
objNode.Text = strData
DecodeBase64 = objNode.nodeTypedValue
'clean up
Set objNode = Nothing
Set objXML = Nothing
End Function
Points need to take care of for pdf to base64
If you are converting the pdf to base64/blob for rest API then do not use string variables because the size of a string variable is 32200 only.
If you are using pdf for rest API then you need to read the pdf in binary-only [ do not read it by text]
In VBA JSON file is sent through the text-only so try to use the streams instead of the JSON file.
I am sharing the code which does the binary conversion of base64 of the pdf file.
Function EncodeFileBase64(FileName As String) As String
fileNum = FreeFile
Open FileName For Binary As fileNum
ReDim arrData(LOF(fileNum) - 1)
Get fileNum, , arrData
Close fileNum
Set objXML = New MSXML2.DOMDocument
Set objNode = objXML.createElement("b64")
objNode.DataType = "bin.base64"
objNode.nodeTypedValue = arrData
EncodeFileBase64 = objNode.text
EncodeFileBase64 = Replace(objNode.text, vbLf, "")
Set objNode = Nothing
Set objXML = Nothing
End Function
I have an ASP .NET Web Form application to upload files to a MySql 5.5 table.
When I click the submit button the query is executed but in the table only the Identity column gets a value.
The columns for the file attributes i.e FileName(varchar (50)) , ContentType(varchar (50))
and Content (medium blob) are blank. All other controls e.g textboxes execute insert operations from the application except the Asp:FileUpload control.
My code is as below:
Protected Sub UploadFile()
Dim filename As String = Path.GetFileName(fuCollateral.PostedFile.FileName)
Dim contentType As String = fuCollateral.PostedFile.ContentType
Dim iFileLen As Integer
Dim byteFileData As Byte()
Dim uploadedFile As HttpPostedFile = fuCollateral.PostedFile
If fuCollateral.HasFile Then
uploadedFile = fuCollateral.PostedFile
iFileLen = uploadedFile.ContentLength
ReDim byteFileData(iFileLen)
uploadedFile.InputStream.Read(byteFileData, 0, iFileLen)
Using fs As Stream = fuCollateral.PostedFile.InputStream
Using br As New BinaryReader(fs)
Dim bytes As Byte() = br.ReadBytes(DirectCast(fs.Length, Long))
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New MySqlConnection(constr)
Dim query As String = "INSERT INTO imagefiles(FileName, ContentType, Content) VALUES (#FileName, #ContentType, #Content)"
Using cmd As New MySqlCommand(query)
cmd.Connection = con
cmd.Parameters.Add(New MySqlParameter("#FileName", filename))
cmd.Parameters.Add(New MySqlParameter("#ContentType", contentType))
cmd.Parameters.Add(New MySqlParameter("#Content", bytes))
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
End Using
End Using
End If
End Sub
The code of the button click event:
Protected Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
UploadFile()
End Sub
Screenshot of table after clicking submit:
enter image description here
Here I would like to ask, how to display the image data into DevExpress DevExpress gridview or CardView.
For I will take a picture of data from mysql database that I keep with BLOB data type.
how or its code if using visual basic.?
for Code that I use:
Dim Query As String = "SELECT FTO.ALM_NIM as FOTO_ID, FTO.ALM_FOTO as FOTO FROM tbl_foto_alumni as FTO"
Using DA As New MySql.Data.MySqlClient.MySqlDataAdapter(Query, MyKonection)
Dim DTwisda As New DataTable
DA.Fill(DTwisda)
if Dtwisda.Rows.Count > 0 Then
GridControl.Datasource = DTwisda
MainView = CardView1
Dim RepItemImg As New Repository.RepositoryItemPictureEdit()
RepItemImg.SizeMode = DevExpress.XtraEditors.Controls.PictureSizeMode.Stretch
RepItemImg.BestFitWidth = 100
RepItemImg.CustomHeight = 150
With CardView1.Columns("FOTO")
.ColumnEdit = RepItemImg
End With
With CardView1
.OptionsBehavior.FieldAutoHeight = True
.MaximumCardRows = 2
.MaximumCardColumns = 6
End With
End If
End Using
To Screnshoot my program and the results of calling the data from the database, Please Check The Attachment.
already I attach the following word file.
ScreenShoot_Program
Please Help and Give The Solution.
Regards,
Tafary
Try This Code:
Dim row As DataRow
Dim i As Integer
For Each row In myDt.Rows
Column = New DataColumn
With Column
.DataType = GetType(Bitmap)
' .DefaultValue = Base64ToImage(row("Photo"))
.Unique = False
.ColumnName = "EmpPhoto"
End With
If Not myDt.Columns.Contains("EmpPhoto") Then
myDt.Columns.Add(Column)
End If
myDt.Rows(i)("EmpPhoto") = Base64ToImage(row("Photo"))
i += 1
myDt.AcceptChanges()
Next
i = 0
'myDt.Rows.Add(Column.DefaultValue)
Public Function Base64ToImage(base64String As String) As Image
Try
' Convert Base64 String to byte[]
Dim imageBytes As Byte() = Convert.FromBase64String(base64String)
Dim ms As New MemoryStream(imageBytes, 0, imageBytes.Length)
' Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length)
Dim image1 As Image = Image.FromStream(ms, True)
Return image1
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Function
I have a simple form created in Visual Studio (VB) which has a data gridview connected to a table in MySQL (hosted in a remote server).
I have the below code to export the grid view to Excel but it takes a really long time to export (around 15 minutes).
The table in MySQL is really small (1000 rows and 60 columns).
Is there a better way to export the complete MySQL table to excel?
PLEASE HELP
CODE:
Dim xlApp As Microsoft.Office.Interop.Excel.Application
Dim xlWorkBook As Microsoft.Office.Interop.Excel.Workbook
Dim xlWorkSheet As Microsoft.Office.Interop.Excel.Worksheet
Dim misValue As Object = System.Reflection.Missing.Value
Dim i As Integer
Dim j As Integer
xlApp = New Microsoft.Office.Interop.Excel.Application
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
For i = 0 To DataGridView1.Rows.Count - 1
For j = 0 To DataGridView1.Columns.Count - 1
For k As Integer = 1 To DataGridView1.Columns.Count
On Error Resume Next
xlWorkSheet.Cells(1, k) = DataGridView1.Columns(k - 1).HeaderText
xlWorkSheet.Cells(i + 2, j + 1) = DataGridView1(j, i).Value.ToString()
Next
Next
Next
xlWorkSheet.SaveAs("C:\Users\USERNAME\Desktop\vbexcel.xlsx")
xlWorkBook.Close()
Is there two ways to do this :
using rdlc reports.
using gridview exporting.
first way you need to created rdlc report, then retrieving data into datatable, then call this code:
Dim MyDataSource As ReportDataSource = New ReportDataSource("ReportDataSet", MyDataTable)
reportviewer1.LocalReport.ReportPath = Server.MapPath("MyrdlcReportPath")
rvSmartCardsIssues.LocalReport.EnableExternalImages = True
rvSmartCardsIssues.LocalReport.DataSources.Clear()
rvSmartCardsIssues.LocalReport.DataSources.Add(MyDataSource )
rvSmartCardsIssues.LocalReport.Refresh()
Dim warnings As Warning() = Nothing
Dim streamids As String() = Nothing
Dim mimeType As String = Nothing
Dim encoding As String = Nothing
Dim extension As String = Nothing
Dim bytes As Byte()
bytes = rvSmartCardsIssues.LocalReport.Render("Excel", Nothing, mimeType, encoding, extension, streamids, warnings)
HttpContext.Current.Response.Buffer = True
HttpContext.Current.Response.Clear()
HttpContext.Current.Response.ContentType = mimeType
HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=ExportedFileName.xls")
HttpContext.Current.Response.BinaryWrite(bytes)
HttpContext.Current.Response.Flush()
HttpContext.Current.Response.End()
second way that based on this function :
Public Shared Sub ExportGridViewToExcelGridView(ByVal Filename As String, ByRef gvr As GridView, ByRef currentPage As Page)
Dim HtmlForm As System.Web.UI.HtmlControls.HtmlForm = New System.Web.UI.HtmlControls.HtmlForm()
currentPage.Controls.Add(HtmlForm)
HtmlForm.Controls.Add(gvr)
currentPage.Response.Clear()
currentPage.Response.Buffer = True
currentPage.Response.AddHeader("Content-Disposition", "attachment; filename=" & Filename)
currentPage.Response.ContentType = "application/vnd.ms-excel"
currentPage.Response.ContentEncoding = System.Text.Encoding.UTF8
currentPage.Response.Charset = ""
currentPage.EnableViewState = False
Using strwriter As New StringWriter
Dim htmlwrt As HtmlTextWriter = New HtmlTextWriter(strwriter)
HtmlForm.RenderControl(htmlwrt)
htmlwrt.Flush()
currentPage.Response.Write(strwriter.ToString)
currentPage.Response.End()
End Using
End Sub
make sure that when you use second way to set the gridview paging property to false.
I've wrote a script to create a HTML file based on a SQL Query.... It has become necessary to have that HTML be emailed. Most of our execs use blackberry's and I want to send the HTML file as the body. I have found a round about way to get this done, by adding a WebBrowser, and having the web browser then load the file, and then using the below code to send. The problem i'm facing is if I automate the code fully, it will only email part of the HTML document, now if I add a button, and make it do the email function, it sends correctly. I have added a wait function in several different location, thinking it may be an issue with the HTML not being fully created before emailing. I have to get this 100% automated. Is there a way I can use the .HTMLBody to link to the actual HTML file stored on the C:(actual path is C:\Turnover.html). Thanks all for any help.
Public Sub Email()
Dim strdate
Dim iCfg As Object
Dim iMsg As Object
strdate = Date.Today.TimeOfDay
iCfg = CreateObject("CDO.Configuration")
iMsg = CreateObject("CDO.Message")
With iCfg.Fields
.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 1
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "xxxxx.com"
.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
.Item("http://schemas.microsoft.com/cdo/configuration/sendemailaddress") = """Turnover Report"" <TurnoverReports#xxxxx.com>"
.Update()
End With
With iMsg
.Configuration = iCfg
.Subject = "Turnover Report"
.To = "xxxxx#xxxxx.com"
'.Cc = ""
.HTMLBody = WebBrowserReportView.DocumentText
.Send()
End With
iMsg = Nothing
iCfg = Nothing
End Sub
used the below function to read in a local html file. then set
TextBox2.Text = getHTML("C:\Turnover2.html")
and also
.HTMLBody = TextBox2.Text
Private Function getHTML(ByVal address As String) As String
Dim rt As String = ""
Dim wRequest As WebRequest
Dim wResponse As WebResponse
Dim SR As StreamReader
wrequest = WebRequest.Create(address)
wResponse = wrequest.GetResponse
SR = New StreamReader(wResponse.GetResponseStream)
rt = SR.ReadToEnd
SR.Close()
Return rt
End Function