parameter is not valid for image.fromstream() - vb.net

Dim strsql As String
get data from access database in vb.net
Dim stream As System.IO.MemoryStream
Dim img As Image
strsql = " select HotelName,HotelAddress,HotelPhoneNum,HotelPicture,HotelDesc from Hotel_3Star where ID = " & intIndex & ";"
Dim cmd As New OleDbCommand(strsql, connection)
Dim myreader As OleDbDataReader
myreader = cmd.ExecuteReader
myreader.Read()
Dim nameHotel As String = myreader("HotelName")
Dim phoneNumHotel As String = myreader("HotelPhoneNum")
Dim descHotel As String = myreader("HotelDesc")
Dim PictHotel = myreader("HotelPicture")
stream = New System.IO.MemoryStream(CType(PictHotel, Byte()))
it says that the parameter is not valid
img = Image.FromStream(stream) 'here the error detected
lblHotelName.Text = nameHotel
lblPhoneNum.Text = phoneNumHotel
lblHotelDesc.Text = descHotel
pcbHotel.Image = img
connection.Close()

Related

how to put numbering for Images in Listview

How to add numbering Images in Listview and below attached the code.
Private Sub retrieve()
ListView1.Clear()
Dim imglist As New ImageList
imglist.ColorDepth = ColorDepth.Depth32Bit
ListView1.LargeImageList = imglist
ListView1.LargeImageList.ImageSize = New System.Drawing.Size(200, 200)
Dim strsql As String = "select * from picEmploy where NumFile=" & TextBox1.Text
Dim dt_images As New DataTable
cmd.Connection = con
cmd.CommandText = strsql
adp.SelectCommand = cmd
adp.Fill(ds)
For Each dr As DataRow In ds.Tables(0).Rows
Dim imb_buffer = CType(dr("pic"), Byte())
Dim img_stream As New IO.MemoryStream(imb_buffer, True)
img_stream.Write(imb_buffer, 0, imb_buffer.Length)
imglist.Images.Add(dr("NumFile").ToString(), New Bitmap(img_stream))
img_stream.Close()
Dim lsvparent As New ListViewItem
'lsvparent.Text = dr("pic").ToString
lsvparent.ImageKey = dr("NumFile").ToString
ListView1.Items.Add(lsvparent)
Next
End Sub

asp.net vb Button.click insert to sql working at client but not working when move to server

This code is working a PC. I have filled grid view with the dataset, so I suppose I can read Excel.
However, the insert to sql part is not working when I copy the code to the server and I don't know why. It is not throwing any errors.
I removed the try catch lines but still, there are no errors.
I am adding new code block, I did a test and wrote a siple insert code like;
Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim mysql_connection As New SqlConnection
mysql_connection.ConnectionString = "Data Source=SRV01;Initial Catalog=TR_Development;Persist Security Info=True;User ID=sa"
Dim command As String = "insert into gez_test (test) values ('c')"
Dim mysqlcommand As New SqlCommand
mysqlcommand.CommandType = CommandType.Text
mysqlcommand.CommandText = command
mysqlcommand.Connection = mysql_connection
If mysql_connection.State = ConnectionState.Closed Then mysql_connection.Open()
mysqlcommand.ExecuteNonQuery()
If mysql_connection.State = ConnectionState.Open Then mysql_connection.Close()
End Sub
And at server it is not inserting. What can be the problem any idea?
Orginal code
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles
Button1.Click
Dim path_ As String = "\\exchange\COMPANY\web\" + FileUpload1.FileName
FileUpload1.PostedFile.SaveAs(path_)
Dim identifier As Boolean = False
Dim connStr As String = "provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + path_ + "';Extended Properties=Excel 12.0;"
Dim MyConnection As OleDbConnection
Dim ds As DataSet
Dim MyCommand As OleDbDataAdapter
MyConnection = New OleDbConnection(connStr)
MyConnection.Open()
Dim dtSheets As DataTable = MyConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
Dim listSheet As New List(Of String)
Dim drSheet As DataRow
For Each drSheet In dtSheets.Rows
listSheet.Add(drSheet("TABLE_NAME").ToString())
Next
For Each sheet As String In listSheet
If sheet = "'BAS+Surcharges$'" Then
identifier = True
Exit For
End If
Next
If identifier = True Then
MyCommand = New OleDbDataAdapter("select * from [BAS+Surcharges$]", MyConnection)
ds = New System.Data.DataSet()
MyCommand.Fill(ds)
MyConnection.Close()
'**************SQL***************
Dim line, columns As Integer
line = ds.Tables(0).Rows.Count
columns = ds.Tables(0).Columns.Count
Label1.Text = line.ToString
ASPxTextBox1.Text = line.ToString
If line > 0 And columns = 16 Then
Dim command As String = "exec SP_INTRA_EXCEL_LINE_INSERT" _
+ " #line_isim, #nereden, #via, #nereye, #transit_sure, #baslangic_tarihi," _
+ "#e_kadar_gecerli, #kalem_kodu, #fiyatlandirma, #20DRY, #40DRY, #40HDRY," _
+ "#40HREF_NOR, #kayit_eden"
Dim mysql_connection As New SqlConnection
mysql_connection.ConnectionString = ConfigurationManager.ConnectionStrings("TR_DevelopmentConnectionString").ConnectionString
Dim mysqlcommand As New SqlCommand
mysqlcommand.CommandType = CommandType.Text
mysqlcommand.CommandText = command
mysqlcommand.Connection = mysql_connection
Dim line_isim, nereden, via, nereye, transit_sure, baslangic_tarihi, e_kadar_gecerli,
kalem_kodu, fiyatlandirma, _20DRY, _40DRY, _40HDRY,
_40HREF_NOR, kayit_eden As String
If mysql_connection.State = ConnectionState.Closed Then mysql_connection.Open()
For i = 6 To line - 1
line_isim = ds.Tables(0).Rows(i).Item(13).ToString
nereden = ds.Tables(0).Rows(i).Item(0).ToString
via = ds.Tables(0).Rows(i).Item(14).ToString
nereye = ds.Tables(0).Rows(i).Item(1).ToString
transit_sure = ds.Tables(0).Rows(i).Item(15).ToString
baslangic_tarihi = Convert.ToDateTime(ds.Tables(0).Rows(i).Item(2).ToString).ToString
e_kadar_gecerli = Convert.ToDateTime(ds.Tables(0).Rows(i).Item(3).ToString).ToString
kalem_kodu = ds.Tables(0).Rows(i).Item(7).ToString
fiyatlandirma = ds.Tables(0).Rows(i).Item(8).ToString
_20DRY = ds.Tables(0).Rows(i).Item(9).ToString
_40DRY = ds.Tables(0).Rows(i).Item(10).ToString
_40HDRY = ds.Tables(0).Rows(i).Item(11).ToString
_40HREF_NOR = ds.Tables(0).Rows(i).Item(12).ToString
kayit_eden = Environment.UserName.ToString
mysqlcommand.Parameters.AddWithValue("#line_isim", line_isim)
mysqlcommand.Parameters.AddWithValue("#nereden", nereden)
mysqlcommand.Parameters.AddWithValue("#via", via)
mysqlcommand.Parameters.AddWithValue("#nereye", nereye)
mysqlcommand.Parameters.AddWithValue("#transit_sure", transit_sure)
mysqlcommand.Parameters.AddWithValue("#baslangic_tarihi", baslangic_tarihi)
mysqlcommand.Parameters.AddWithValue("#e_kadar_gecerli", e_kadar_gecerli)
mysqlcommand.Parameters.AddWithValue("#kalem_kodu", kalem_kodu)
mysqlcommand.Parameters.AddWithValue("#fiyatlandirma", fiyatlandirma)
mysqlcommand.Parameters.AddWithValue("#20DRY", _20DRY)
mysqlcommand.Parameters.AddWithValue("#40DRY", _40DRY)
mysqlcommand.Parameters.AddWithValue("#40HDRY", _40HDRY)
mysqlcommand.Parameters.AddWithValue("#40HREF_NOR", _40HREF_NOR)
mysqlcommand.Parameters.AddWithValue("#kayit_eden", kayit_eden)
mysqlcommand.ExecuteNonQuery()
mysqlcommand.Parameters.Clear()
Next
If mysql_connection.State = ConnectionState.Open Then mysql_connection.Close()
End If
End If
ASPxGridView1.DataBind()

When I try to pull nvarchar column value that has an emojis stored in it, the data in VB.net it displays as '??'

When I try to pull the emoji value from the database using VB.net the emoji is displayed as '??'
Is there some sort of conversion I need to do in my stored procedure?
Private Function DisplayEmoji(input As String) As String
Dim output As New StringBuilder()
Dim enumerator = StringInfo.GetTextElementEnumerator(input)
While enumerator.MoveNext()
Dim chunk As String = enumerator.GetTextElement()
If Char.IsSurrogatePair(chunk, 0) Then
output.Append("<img src=""" + "https://abs.twimg.com/emoji/v1/72x72/" + Char.ConvertToUtf32(chunk, 0).ToString("x") + ".png"" style=""height:1.5em; width:1.5em;"">")
Else
output.Append(chunk)
End If
End While
Return output.ToString()
End Function
Or insert your image Blob type and read sql.
Dim filePath As String = Server.MapPath("APP_DATA/test.png")
Dim filename As String = Path.GetFileName(filePath)
Dim fs As FileStream = New FileStream(filePath, FileMode.Open, FileAccess.Read)
Dim br As BinaryReader = New BinaryReader(fs)
Dim bytes As Byte() = br.ReadBytes(Convert.ToInt32(fs.Length))
br.Close()
fs.Close()
Insert to Database yor image
Dim strQuery As String = "insert into tblFiles(Name, ContentType, Data) values (#Name, #ContentType, #Data)"
Dim cmd As SqlCommand = New SqlCommand(strQuery)
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = filename
cmd.Parameters.Add("#ContentType", SqlDbType.VarChar).Value = "image/png"
cmd.Parameters.Add("#Data", SqlDbType.Binary).Value = bytes
InsertUpdateData(cmd)
InsertUpdateData
Public Function InsertUpdateData(ByVal cmd As SqlCommand) As Boolean
Dim strConnString As String = System.Configuration.
ConfigurationManager.ConnectionStrings("conString").ConnectionString
Dim con As New SqlConnection(strConnString)
cmd.CommandType = CommandType.Text
cmd.Connection = con
Try
con.Open()
cmd.ExecuteNonQuery()
Return True
Catch ex As Exception
Response.Write(ex.Message)
Return False
Finally
con.Close()
con.Dispose()
End Try
End Function

How to change value of /GrpPwd/ Cell in all Rows?

I need to perform this SQL Query:
UPDATE Resurses SET GrpPwd = #GrpPwd1 WHERE Resurs = #Resurs1
For all rows in my Access Database using VB.NET
How can i do it?
I use this code but id doesn't work:
Password Generator:
Dim charset As String = nalf
Dim r As New Random()
Dim lenPass As Integer = r.Next(minLength, maxLength)
Dim str As String = String.Empty
For i As Integer = 0 To lenPass - 1
str += charset(r.Next(0, charset.Length))
Next
Return str
End Function
Update rows
If DataGridView1.CurrentRow.Cells(3).Value = "Yes" Then
nres = DataGridView1.CurrentRow.Cells(0).Value
nalf = DataGridView1.CurrentRow.Cells(6).Value
nsym = DataGridView1.CurrentRow.Cells(1).Value
Dim parol1 As String
Dim pwd As String = pass99(nsym, nsym) '
parol1 = pwd
Dim cmd As New OleDbCommand()
Dim Conn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.oledb.12.0; Data source=" + bpath)
cmd.Connection = Conn
Conn.Open()
For i As Integer = 0 To k - 1
cmd.CommandText = String.Format("UPDATE Resurses SET GrpPwd = #GrpPwd1{0} WHERE Resurs = #Resurs1{0};", i)
cmd.Parameters.Add(String.Format("#GrpPwd1{0}", i), OleDbType.WChar).Value = parol1
cmd.Parameters.Add(String.Format("#Resurs1{0}", i), OleDbType.Integer).Value = nres
Next
cmd.ExecuteNonQuery()
Conn.Close()
MsgBox("All rows are updated!")
End If
f

How to add image from database to PictureBox?

I am using this to get image bytes from the database
cmd.CommandText = "select imagedate from projectimages where imagename = '" + _
ListBox1.Text + "' and CSVprojectref=checksum('" + textboxFileRef.Text + "')"
Dim img As Object = cmd.ExecuteScalar()
Now how can I add this to PictureBox.image. I am having a lot of trouble retrieving the image and displaying it in the PictureBox.
The datatype is Image in sql database and i use this code to save image to db
Dim ms As New IO.MemoryStream
If imageFilename.Contains("jpeg") Or imageFilename.Contains("jpg") Then
imageUpload.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)
End If
If imageFilename.Contains("png") Then
imageUpload.Save(ms, System.Drawing.Imaging.ImageFormat.Png)
End If
If imageFilename.Contains("gif") Then
imageUpload.Save(ms, System.Drawing.Imaging.ImageFormat.Gif)
End If
If imageFilename.Contains("bmp") Then
imageUpload.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp)
End If
Dim bytes() As Byte = ms.ToArray
Dim img As String = Convert.ToBase64String(bytes)
Dim cmd As New OleDb.OleDbCommand("insert projectimages values('" + imageNameTemp + "','" + img + "',CHECKSUM('" + textboxFileRef.Text + "'))", con)
cmd.ExecuteNonQuery()
After 5-6 hours of searching forums and blogs and everything i fond this... to save image to database
1- datatype should be image in database
Now add this code when storing image to the sql database
OpenFileDialog1.ShowDialog()
imageFilename = OpenFileDialog1.FileName
Dim imageUpload As Image
imageUpload = Image.FromFile(OpenFileDialog1.FileName)
If imageFilename <> "" Then
Dim imageNameTemp As String
imageNameTemp = imageFilename
While (imageNameTemp.Contains("\"))
imageNameTemp = imageNameTemp.Remove(0, imageNameTemp.IndexOf("\") + 1)
End While
Dim ms As New IO.MemoryStream
If imageFilename.Contains("jpeg") Or imageFilename.Contains("jpg") Then
imageUpload.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)
End If
If imageFilename.Contains("png") Then
imageUpload.Save(ms, System.Drawing.Imaging.ImageFormat.Png)
End If
If imageFilename.Contains("gif") Then
imageUpload.Save(ms, System.Drawing.Imaging.ImageFormat.Gif)
End If
If imageFilename.Contains("bmp") Then
imageUpload.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp)
End If
'Dim cmd As New SqlCommand("INSERT INTO projectimages (imagename,imagedate,csvprojectref) VALUES ('" + imageFilename + "',#BLOBData,CHECKSUM('" + textboxFileRef.Text + "'))", con)
Dim b() As Byte = ms.ToArray()
Dim cmd As New SqlCommand("INSERT INTO projectimages (imagename,imagedate,csvprojectref) VALUES ('" + imageNameTemp + "',#BLOBData,CHECKSUM('" + textboxFileRef.Text + "'))", con)
cmd.Parameters.Add("#BLOBData", SqlDbType.Image, b.Length).Value = b
' Dim cmd As New SqlCommand("insert projectimages(imagename,imagedate,csvprojectref) values('imagma','" + img + "',CHECKSUM('" + textboxFileRef.Text + "'))", con)
cmd.ExecuteNonQuery()
' cmdTemp.Parameters.Add("#photo", SqlDbType.Image, b.Length).Value = b
End If
And when to retrieve data to insert into picture box use this code...
cmd.CommandText = "select imagedate from projectimages where imagename = '" + ListBox1.Text + "' and CSVprojectref=checksum('" + textboxFileRef.Text + "')"
cmd.Connection = con
Dim da As New SqlDataAdapter(cmd)
Dim ds As New DataSet()
da.Fill(ds, "projectimages")
Dim c As Integer = ds.Tables(0).Rows.Count
If c > 0 Then
Dim bytBLOBData() As Byte = _
ds.Tables(0).Rows(c - 1)("imagedate")
Dim stmBLOBData As New MemoryStream(bytBLOBData)
PictureBox1.Image = Image.FromStream(stmBLOBData)
End If
Use a MemoryStream object as per Microsoft.
Dim img As Byte() = DirectCast(cmd.ExecuteScalar(), Byte())
Dim ms as MemoryStream = New MemoryStream(img)
pictureBox.Image = Image.FromStream(ms)
assuming imagedate field a blob field.
here's my code to show blob file to picturebox in vb.net. hope it helps
Dim connstring As String = "Database=pmk;data source=localhost;user id=root;password="
Dim Sql As String = "select * from mastermahasiswa where Nim='" & TextBox1.Text & "'"
Dim conn As New MySqlConnection(connstring)
Dim cmd As New MySqlCommand(Sql, conn)
Dim dr As MySqlDataReader = Nothing
conn.Open()
dr = cmd.ExecuteReader()
dr.Read()
Dim imagebytes As Byte() = CType(dr("Foto"), Byte())
Using ms As New IO.MemoryStream(imagebytes)
PictureBox1.Image = Image.FromStream(ms)
PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage
End Using
conn.Close()
I was getting the parameter not valid error as well. To fix, I added a picturebox to my form that loads the image I'm copying to the SQL server as a background image. This statement seems to be key:
PictureBox1.BackgroundImage.Save(ms, PictureBox1.BackgroundImage.RawFormat)
It makes the actual upload take a lot longer, but I'm no longer getting the parameter error... I think because the pictures are actually valid images now.
SSScmd.CommandText = "INSERT INTO PreviewSlideshow (Name, Photo) VALUES (#name, #photo)"
Dim p As New SqlParameter("#photo", SqlDbType.Image)
For Each CurFile As IO.FileInfo In New IO.DirectoryInfo(sSourcePath).GetFiles
If CurFile.Name = "Thumbs.db" Then
'skip
Else
If CurFile.Extension = "jpg" Or CurFile.Extension = "png" Then
'show the image name on the form
ImageName.Text = CurFile.Name
SSScmd.Parameters.AddWithValue("#name", ImageName.Text)
Dim ms As New MemoryStream()
PictureBox1.BackgroundImage = Image.FromFile(sSourcePath & CurFile.Name)
PictureBox1.BackgroundImageLayout = ImageLayout.Stretch
PictureBox1.BackgroundImage.Save(ms, PictureBox1.BackgroundImage.RawFormat)
Dim data As Byte() = ms.GetBuffer()
p.Value = data
SSScmd.Parameters.Add(p)
SSScmd.ExecuteNonQuery()
SSScmd.Parameters.Clear()
End If
End If
Next