Retrieve rtf text with images stored in SQL Server database - asp.net

I want to retrieve rtf text with images stored in SQL Server database with Windows form in asp.net web form with exactly format and images.
This is the code to store in Windows form:
Dim cmd As New SqlCommand("UPDATE questions SET ques_rich = #ques_rich WHERE quest_no = 1 ", con)
con.Open()
cmd.Parameters.AddWithValue("#ques_rich", RichTextBox1.Rtf)
cmd.ExecuteNonQuery()
con.Close()
This is the code used to retrieve in asp.net:
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim con As New SqlConnection("Data Source=AHMEDHASHEM\SQLEXPRESS;Initial Catalog=test;Integrated Security=True")
Dim cmd1 As New SqlClient.SqlCommand
Dim tbl As New DataTable
Dim reader As SqlClient.SqlDataReader
Dim sql As String
sql = "select * from questions where quest_no = 1"
cmd1 = New SqlClient.SqlCommand(sql, con)
Dim ds1 As New DataSet()
Dim Adpt1 As New SqlDataAdapter(sql, con)
Adpt1.Fill(ds1, "questions")
'rc = ds1.Tables(0).Rows.Count
con.Open()
tbxTinymce.Text = ds1.Tables("questions").Rows(0)("ques_rich")
con.Close()
End Sub
Note: I use tinymce and freetextbox controls
Also use Word document with this code:
Dim wordApp As New Microsoft.Office.Interop.Word.ApplicationClass()
Dim nullobj As Object = System.Reflection.Missing.Value
Dim doc As Word.Document = wordApp.Documents.Open("c:\goinstall.doc")
Dim doc1 As Word.Document = wordApp.ActiveDocument
Dim m_Content As String = doc1.Content.Text
FreeTextBox1.Text = m_Content
doc.Close(nullobj, nullobj, nullobj)
That code retrieves text only without images and formatting

The following code accepts an image from a file upload stream, converts it to a byte array and stores it in the session object for later retrieval and storage into a blob in a Oracle database.
' Easy enough to load a file from a stream, here I get a image from a file upload
Dim TheStream As Stream = file1.PostedFile.InputStream
' Need a variable to store the image in
Dim origimage As System.Drawing.Image
' Same the uploaded image to the variable
origimage = System.Drawing.Image.FromStream(TheStream)
' Now we need to convert it to a bye array
Dim ms2 As New System.IO.MemoryStream
' First I scale it, I don't need a huge image, you won't need to do this
origimage = ScaleImage(origimage, 320, 200) ' new scaling method
' I save it to the memory stream in preparation to converting to a byte array
origimage.Save(ms2, Imaging.ImageFormat.Jpeg)
' Here I convert the file
Dim MyPhoto() As Byte = ms2.GetBuffer ' The scaled image is now stored in memory as a byte array
Session("ThePhoto") = MyPhoto ' put it into the session to retreive later
' Release the memory
ms2.Dispose()
origimage.Dispose()
Obviously some of this won't be relevant to your problem. You need to load your RTF file using a filestream of some sort and then convert the file to a byte array. Hopefully this will help to point you in the right direction.

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)

Error to convert the binary to image

I try to import the image from mssql varbinary(max) column to iTextSharp.
But it always shows the error "NullReferenceException" on the "phrase.Add(imageChunk)"
My code is:
Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("dbconnection").ConnectionString)
Dim q As String = "select top 1 pic_id from pic"
Dim cmd As SqlCommand = New SqlCommand(q, conn)
conn.Open()
Dim sr As SqlDataReader = cmd.ExecuteReader
While sr.Read
Dim byt() As Byte = CType(sr.Item("pic_id"), Byte())
Dim ms As MemoryStream = New MemoryStream(byt)
Dim sdi As System.Drawing.Image = System.Drawing.Image.FromStream(ms)
Dim img As Image = Image.GetInstance(sdi, ImageFormat.Jpeg)
Dim imageChunk As Chunk = New Chunk(img, 0, 0)
phrase.Add(imageChunk)
End While
The data type of that column is "varbinary(max)" and the data is like this: (0x89504E470D0A1A0A0000000D494....................)
Your variable "phrase" is not set, it's Nothing/null. Make sure to pass correct "phrase" to your method and it will quite likely fix your problem.

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 save Telerik RadBinaryImage image to SQL Server database

I have a Telerik RadBinaryImage control which is displaying an image loaded using Telerik RadAsyncUpload.
I have an SQL table containing a 'Photo' column (image data type). I want to save to the database the image from the Telerik RadBinaryImage to the insert function which look like this:
Private Sub InsertPhotoIntoDB()
Dim sMyConn As String = My.Settings.appDBConnString
Dim myConnection As SqlConnection
Dim myCommand As New SqlCommand
myConnection = New SqlConnection(sMyConn)
myConnection.Open()
myCommand = New SqlCommand("INSERT INTO Photos(Photo) VALUES(#Photo)")
myCommand.Connection = myConnection
myCommand.Parameters.Add("#Photo", SqlDbType.Image, 0, "Photo")
myCommand.Parameters("#Photo").Value = WhatDoIPutHere???
myCommand.ExecuteNonQuery()
myConnection.Close()
myConnection.Dispose()
End Sub
I've tried:
myCommand.Parameters.Add("#Photo", SqlDbType.Image).Value = RadBinaryImage1.DataValue
but I still get an error:
The parameterized query '(#Photo image)INSERT INTO Photos (Photo) VALUES (#Photo)' expects parameter '#Photo', which was not supplied.
Do I need to convert RadBinaryImage1.DataValue to image?
The RadBinaryImage control is used to display an image coming from the database. So, the sequence should be like this:
User uploads photo via RadUpload
Image stored in database using modified code (see below)
On PostBack, the page displays the image from the database using the RadBinaryImage
If you don't want to store in the database right away, you will need to persist the data yourself in some way (Could store the file on the filesystem and then access the path via RadBinaryImage.SavedImageName, or persist in memory as Session["UploadedImage"]). The bottom line is RadBinaryImage is only meant to display an image on the page.
With regards to your sample code, I recommend using the SQL column type varbinary instead of image.
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles Button1.Click
For Each file As UploadedFile In RadUpload1.UploadedFiles
Dim bytes(file.ContentLength - 1) As Byte
file.InputStream.Read(bytes, 0, file.ContentLength)
Dim connection As OleDbConnection = CreateConnection()
Try
Dim command As New OleDbCommand("INSERT INTO Images ([Name], [Size], [Content]) VALUES (?, ?, ?)", connection)
command.Parameters.AddWithValue("#Name", file.GetName())
command.Parameters.AddWithValue("#Size", bytes.Length)
command.Parameters.AddWithValue("#Content", bytes)
connection.Open()
command.ExecuteNonQuery()
Finally
If connection.State = Data.ConnectionState.Open Then
connection.Close()
End If
End Try
Next
End Sub
See this post for sample code and more explanation:
http://www.telerik.com/help/aspnet-ajax/upload-manipulating-files.html
The safest way is to upload the image as a byte array:
Byte[] yourByteArray;
...
myCommand.Parameters.AddWithValue("#Photo", yourByteArray);
How to get to a byte array differs. With the ASP.NET Upload control, it's just:
yourByteArray = FileUpload1.FileBytes;
Or if the image is represented as a stream:
var yourByteArray = new Byte[ImageObject.InputStream.Length];
ImageObject.InputStream.Read(yourByteArray, 0, yourByteArray.Length);

how to maintain connection with excel with rapidly data fetching

i am making a website for trading, with trading feeds coming from a source in an excel sheet. I have to show data from the excel sheet in a gridview. When i make connection it will fail due to rapidly changing data; each cell in the sheet changes value 1-3 times per second. I am using an Ajax Timer of interval 100. Here is my code:
Public Function RetrieveExcelData(ByVal excelSheetName As String, ByVal sheetNumber As Integer) As DataSet
Dim objConn As OleDbConnection = Nothing
Dim dt As System.Data.DataTable = Nothing
Try
' Connection String.
Dim connString As [String] = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=C:\Users\Vishal\Desktop\TESTING COLOURfor web1.xls;Extended Properties=Excel 8.0;"
' Create connection object by using the preceding connection string.
objConn = New OleDbConnection(connString)
' Open connection with the database.
objConn.Open()
' Get the data table containg the schema guid.
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
If dt Is Nothing Then
Return Nothing
End If
Dim excelSheets As [String]() = New [String](dt.Rows.Count - 1) {}
Dim i As Integer = 0
' Add the sheet name to the string array.
For Each row As DataRow In dt.Rows
excelSheets(i) = row("TABLE_NAME").ToString()
i += 1
If i = sheetNumber Then
Exit For
End If
Next
Dim excelCommand As New OleDbCommand("Select * from [" + excelSheets(sheetNumber - 1) & "]", objConn)
Dim excelAdapter As New OleDbDataAdapter(excelCommand)
Dim excelDataSet As New DataSet()
excelAdapter.Fill(excelDataSet)
Return excelDataSet
Catch ex As OleDbException
Throw ex
Catch ex As Exception
Throw ex
Finally
' Clean up.
If objConn IsNot Nothing Then
objConn.Close()
objConn.Dispose()
End If
If dt IsNot Nothing Then
dt.Dispose()
End If
End Try
End Function
To be honest - I cannot see how it can work. You are trying to use Excel spreadsheet as a database to store and retrieve data in real-time, for which Excel was never intended or designed.
You have mentioned that the Excel gets data several times per second. What is the source of data? RTD component? Bloomberg API? I would try to avoid the middle step of storing data in a spreadsheet.

Resources