How to save Telerik RadBinaryImage image to SQL Server database - asp.net

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);

Related

Retrieve rtf text with images stored in SQL Server database

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.

cannot convert string to date

Hello stack overflow residents! this is my first post and i'm hoping to receive some help.
I've searched but because I'm still very new, i was not able to full find/understand my answer.
I keep encountering this error:
Message: Conversion from string "" to type 'Date' is not valid. File:
~/reports/pendingshipments.aspx Function: btnExportXls_Click Stack
Trace: at
Microsoft.VisualBasic.CompilerServices.Conversions.ToDate(String
Value) at reports_default.btnExportXls_Click(Object sender, EventArgs
e) in C:\Users\jet.jones\Documents\ERIRoot\ERITitan\ERITitan.ssa\Web
Application\reports\pendingshipments.aspx.vb:line 75
Here is my code:
on App_code
**Public Function Reports_PendingShipments(ByVal intClientID As Integer, ByVal strMinDate As Date?, ByVal strMaxDate As Date?, ByVal xmlSiteID As String) As DataTable
'=================================================================================
' Author: Jet Jones
' Create date: 2013.05.28
' Description: Returns a data table with pending shipments for the sites specified
'=================================================================================
Dim objConn As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("Titan").ToString)
Dim cmdGet As New SqlCommand("spReports_PendingShipments", objConn)
Dim parClientID As New SqlParameter("#ClientID", SqlDbType.Int)
Dim parMinDate As New SqlParameter("#MaxDate", IIf(Not strMinDate.HasValue, DBNull.Value, strMinDate))
Dim parMaxDate As New SqlParameter("#MaxDate", IIf(Not strMaxDate.HasValue, DBNull.Value, strMaxDate))
Dim parSiteID As New SqlParameter("#Sites", SqlDbType.Xml)
Dim objAdapter As New SqlDataAdapter(cmdGet)
Dim objTable As New DataTable
parClientID.Value = intClientID
parMinDate.Value = strMinDate
parMaxDate.Value = strMaxDate
parSiteID.Value = xmlSiteID
'set up the command object
cmdGet.Connection = objConn
cmdGet.CommandType = CommandType.StoredProcedure
'add the parameters
cmdGet.Parameters.Add(parClientID)
cmdGet.Parameters.Add(parMinDate)
cmdGet.Parameters.Add(parMaxDate)
cmdGet.Parameters.Add(parSiteID)
'open the connection
objConn.Open()
'execute the query and fill the data table
objAdapter.Fill(objTable)
'return the data table
Reports_PendingShipments = objTable
'clean up
objConn.Close()
objConn = Nothing
End Function**
my aspx.vb page calls this function this way (Get the values from the query):
objTable = Reports_PendingShipments(ucClientSearch.Value,
txtMinDate.Text, txtMaxDate.Text, strSites)
I'm passing the variable strSites because the website permissions allow for users to have access to one or more site locations, and if a report is run and the user selects "All Sites" from the dropdown, I only want to send the sites they have permissions to via XML.
If I'm missing any information please let me know!
anyone's prompt response is so greatly appreciated.
The problem is that your code is expecting empty dates to be NULL, it doesn't check for empty strings. You need something like this:
if len(strMinDate)=0 then
strMinDate = "01/01/1980"
end
Not sure what you want to default the minimum date to, but you need to add code similar to the IF statement above
Be sure to add this code prior to using the variable a few lines later...
First of all, you adding MaxDate parameter twice:
Dim parMinDate As New SqlParameter("#MaxDate", IIf(Not strMinDate.HasValue, DBNull.Value, strMinDate))
Dim parMaxDate As New SqlParameter("#MaxDate", IIf(Not strMaxDate.HasValue, DBNull.Value, strMaxDate))
And moreover, then you setting parameters values wuthout check for HasValue:
parMinDate.Value = strMinDate
parMaxDate.Value = strMaxDate
Remove these lines and fix min date parameter name

How can I make the logged-In name the default option in dropdownlist box?

Experts.
When a user logs into one of our web apps, there is a dropdownlist containing the names of all of our employees.
An employee could log into the system to record his or her entries into the database.
The employee could log the entries for another employee.
So far, an employee has had to select his or her name from the dropdown list and we don't want employees typing their names, just for consistency and to preserve data integrity.
Our problem currently is how to have employee's login name become the default option in the dropdown. The employee can select another name from the list if making the entries for another empployee.
Any ideas how to accomplish this task?
Thanks alot in advance.
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Not IsPostBack Then
Dim s As String
Dim reader As OleDbDataReader
txtFullName.Text = Session.Item("assignedTo").ToString
'Initialize Connection
s = "Select login_id, UserName from tblusers ORDER BY UserName"
Dim connStr As String = ConfigurationManager.ConnectionStrings("allstringconstrng").ConnectionString
Dim conn As New OleDbConnection(connStr)
Dim cmd As New OleDbCommand(s, conn)
'Open the connection
conn.Open()
Try
'Execute the Login command
reader = cmd.ExecuteReader()
'Populate the list of Users
txtLoginName.DataSource = reader
txtLoginName.DataValueField = "login_id"
txtLoginName.DataTextField = "UserName"
txtLoginName.DataBind()
'Close the reader
reader.Close()
Finally
'Close Connection
conn.Close()
End Try
End If
End Sub
<--new code -->
Try
'Execute the Login command
reader = cmd.ExecuteReader()
'Populate the list of Users
Dim currentUserName As String = ""
While reader.Read()
If (reader("login_id").ToString().Equals(currentUserName)) Then
currentUserName = reader("UserName").ToString()
End If
End While
txtLoginName.SelectedValue = currentUserName
'Close the reader
reader.Close()
Finally
'Close Connection
conn.Close()
End Try
you can use Page.User property to get the Name and then assign it to the dropdown's selected Value on Page_Load event.
Could you just simply select it by text after you populate the list? I assume you'll know the login_id once the user logs in, so you could find the username from the results of the query, like so:
UNTESTED:
string currentUserName = "";
While reader.Read()
If (reader("login_id").ToString().Equals(currentUserLogin)) Then
currentUserName = reader("UserName").ToString()
End If
End While
And then, once the list is populated via the results, select the correct user by username.
txtLoginName.Items.FindByValue(UserName).Selected = true;
Or even better yet, since you should already know the login_id, you can simply select by value from the populated drop down list, like so:
txtLoginName.SelectedValue = login_id
It's worth noting that this is making a very big assumption that the login_id will exist in the list. You may want to perform the appropriate check first to see if the login_id exists before selecting.
If you are using forms or windows authentication, wouldn't you just use:
txtLoginName.Text = User.Identity.Name
I believe this will select it if the text is in the list and matches exactly. Or, just use Sam's method. But was it the User.Identity.Name that you were looking for?

Reducing SQL connections to just 1 - ASP.net VB

I am currently working on an asp.net web page with a GridView displaying a table from a database. This GridView has 4 DropDownLists that will be used to filter the data shown on the GridView. When the page loads 4 Sub routines are run, each one connecting to the database with a select statement to fill the DropDownList with relevant filter headings.
Initially, I had one connection with a loop that populated all of the drop downs but these contained duplicates. I then split the filling of each DDL so that the select statements could contain DISTINCT.
I would like (and am sure there is a way here) to be able to populate all of the DDLs with data from one connection.
Code for one connection:
Protected Sub FillDepDDL()
Dim conn As New SqlConnection()
conn.ConnectionString = WebConfigurationManager.ConnectionStrings("TestDBConnectionString").ConnectionString
Dim connection As New SqlConnection(conn.ConnectionString)
connection.Open()
Const FillAllQS As String = "SELECT DISTINCT [Department] FROM [Employees]"
Dim command As New SqlCommand(FillAllQS, connection)
Dim reader As SqlDataReader = command.ExecuteReader()
Dim sel As New ListItem
sel.Text = "Please Select"
sel.Value = "*"
DDLDepartment.Items.Add(sel)
While reader.Read
Dim Deplist As New ListItem()
Deplist.Value = reader("Department")
Deplist.Text = reader("Department")
DDLDepartment.Items.Add(Deplist)
End While
reader.Close()
conn.Close()
End Sub
The other 3 column names: FirstName > DDLFN, LastName > DDLLN, Wage > DDLWag.
This is only a test DB and the princibles learned here will be applied to a larger live project.
I'm sure some guru will be able to work this out easily but I just can't get my head round it even after hours of searching.
Thanks in advance.
I'm adding this in as answer because I cannot format it in a comment, but this doesn't answer the original question of how to write the sql to return all three distinct result sets. Instead, it answers how to rewrite the code you have above so that connections are properly disposed of in case of an exception.
Protected Sub FillDepDDL()
Dim Deplist As ListItem
Dim sel As New ListItem
sel.Text = "Please Select"
sel.Value = "*"
DDLDepartment.Items.Add(sel)
Using conn As New SqlConnection(WebConfigurationManager.ConnecitonString("TestDBConnectionString").ConnectionString)
Using cmd As New SqlCommand("SELECT DISTINCT [Department] FROM [Employees]", conn)
conn.Open()
Using reader = cmd.ExecuteReader()
While reader.Read
Deplist = New ListItem()
Deplist.Value = reader("Department")
Deplist.Text = reader("Department")
DDLDepartment.Items.Add(Deplist)
End While
End Using
End Using
End Using
End Sub
I don't see any reason for you to try to return all three results in a single query. That will just make your code unnecessarily complicated just to save a millisecond or two. Connection pooling handles the creation of connections on the database server for you, so opening a new connection in your code is very fast.

a ButtonField within DataGrid calling Vb.net as Javascript.... for streaming PDF?

I just noticed it last night,
Anyway, let's get to the interesting case here.
I have a ButtonField within DataGrid, and if you notice it here...
The Interface of that ButtonField is looks like a LINK.
But if we hover on it, it appeared as Javascript's call.
Here is the Image ScreenShot
Ya, that's the 1st case.
IT IS a javascript's call.
I didnt notice about it lately. (hehehe).
Then, if we click on that... it would call the createPDF() function. The function behind the scene (which I'm using VB.net) is to execute these code;
Protected Sub createPDF()
Dim document As New Document()
Dim mem As LengthFixingStream = New LengthFixingStream()
' instantiate a iTextSharp.text.pdf.Document
'Dim mem As New MemoryStream()
' PDF data will be written here
PdfWriter.GetInstance(document, mem)
' tie a PdfWriter instance to the stream
document.Open()
Dim titleFont = FontFactory.GetFont("Arial", 18, Font.BOLD)
document.Add(New Paragraph("Northwind Traders Receipt", titleFont))
document.Close()
' automatically closes the attached MemoryStream
Dim docData As Byte() = mem.GetBuffer()
' get the generated PDF as raw data
' write the document data to response stream and set appropriate headers:
Response.AppendHeader("Content-Disposition", "attachment; filename=testdoc.pdf")
Response.ContentType = "application/pdf"
Response.BinaryWrite(docData)
Response.[End]()
End Sub
But somehow... this of course would not deliver the PDF into the browser.
BEcause It's called by Javascript, nor the direct as Hyperlink (normally).
Thus, I'm wondering could we get the ASP.net Call new Window,
and then redirect the createPDF() result into it?
Correct me if i'm wrong...
Here is just some mockup so you get the idea. I haven't tested this. Basically you will have to put the above code in a new page...say "receipt.aspx" and execute it on the load event...you will need to setup an id parameter...if data is being pulled from the db to generate the pdf.
on the button click add the following
Dim sb As New System.Text.StringBuilder()
sb.Append("<script language='javascript'>")
sb.Append("window.open('receipt.aspx.htm?id=123'', 'Receipt',")
sb.Append("'width=800, height=800, menubar=yes, resizable=no');<")
sb.Append("/script>")
Dim t As Type = Me.GetType()
If Not ClientScript.IsStartUpScriptRegistered(t, "PopupScript") Then
ClientScript.RegisterStartUpScript(t, "PopupScript", sb.ToString())
End If
Notice the "id=123" querystring value I am passing to receipt.aspx?
You can then call that in the receipt.aspx page like this
Dim id as String = Request.QueryString("id")
CreatePDF(id)
...shoot! Just realized you are using a Grid...the principle remains the same, just wireup the buttons on RowDataBound event.
Protected Sub GridView_RowDataBound(sender As Object, e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
Dim Id As String = DirectCast(e.Row.Cells(0).FindControl("quotationid"), Label).Text
Dim myButton As New Button
myButton = DirectCast(e.Row.Cells(4).FindControl("btnViewReceipt"), Button)
myButton.Attributes.Add("OnClick", "window.open('receipt.aspx?id=" + id + "','Receipt','scrollbars=yes','width=800,height=800')")
End If
End Sub

Resources