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

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

Related

parameter is not valid for image.fromstream()

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

VB NET check SQL server image data type for null or empty

I need to check for null value of SQL server image data type ,
here is my code :
Dim cmd As New SqlCommand("select id_image1 from work_tbl where
work_id = 12345 ", conn)
Dim stream As New MemoryStream()
conn.Open()
Dim image As Byte() = DirectCast(cmd.ExecuteScalar(), Byte())
stream.Write(image, 0, image.Length)
conn.Close()
Dim bitmap As New Bitmap(stream)
picturebox1.Image = bitmap
I need to stop the procedure with msgbox if my image column is empty .
Dim cmd As New SqlCommand("select id_image1 from work_tbl where
work_id = 12345 ", conn)
Dim stream As New MemoryStream()
conn.Open()
if DBNull(cmd.ExecuteScalar())=false
Dim image As Byte() = DirectCast(cmd.ExecuteScalar(), Byte())
stream.Write(image, 0, image.Length)
Dim bitmap As New Bitmap(stream)
picturebox1.Image = bitmap
end if
conn.Close()

Opening a CSV file as a OLEDB Connection converts file text to double

I'm opening up a couple of CSV files and reading them in as a DataTable per the example I found here. The issue I am running into it the basic query I'm using to import the data is converting the column of IP addresses into Doubles. So I want to read in 10.0.0.1 and it shows up as 10.001. How can I get this column to read in as a string? I would like to not double process the file if I can.
Query I'm using is basic and is as follows:
SELECT * FROM [ComputerList.csv]
Here is my function to open and read the CSV file into a DataTable
Public Function OpenFile(ByVal strFolderPath as String, ByVal strQuery as String) as DataTable
Dim strConn as String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFolderPath & ";Extended Propteries=""text; HDR=Yes;FMT=Delimited"""
Dim conn as OleDb.OleDbConnection = New OleDb.OleDbConnection(strConn)
Try
conn.Open()
Dim cmd as OleDb.OleDbCommand = New OleDb.OleDbCommand(strQuery, conn)
Dim da as OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter()
da.SelectCommand = cmd
Dim ds as DataSet = New DataSet()
da.Fill(ds)
da.Dispose()
return ds.Tables(0)
Catch
return Nothing
Finally
conn.Close()
End Try
End Function
i use this to read csv's and force all to string.
Public Function convert_csv_to_data_table(ByVal File As String, ByVal separator As String) As DataTable
Dim dt As New DataTable
Dim firstLine As Boolean = True
If IO.File.Exists(File) Then
Using sr As New StreamReader(File)
While Not sr.EndOfStream
If firstLine Then
firstLine = False
Dim cols = sr.ReadLine.Split(separator)
For Each col In cols
dt.Columns.Add(New DataColumn(col, GetType(String)))
Next
Else
Dim data() As String = sr.ReadLine.Split(separator)
dt.Rows.Add(data.ToArray)
End If
End While
End Using
End If
Return dt
End Function
EDIT:- this will only work with a separator btw
ok I tried variations of everyone's suggested and have settled on a hybrid between all of them. My goal was to read in a CSV file manipulate it in a DataTable form and them write it back out. Some of my CSV files had multiple lines with in a cell and some had deliminators within a cell. Below you can find my hybrid solution that utilized TextFieldParser to read in the file and break it up.
Public Function OpenFile(ByVal File as String, NyVal delim as String) as DataTable
Dim dt as New DataTable()
Dim firstline as Boolean = True
Using MyReader as New Microsoft.VisualBasic.FileIO.TextFieldParser(File)
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(delim)
Dim currentRow as String()
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
If firstline
firstline = false
For Each col in currentRow
dt.Columns.Add(New DataColumn(col.ToString(), System.Type.GetType("System.String")))
Next
Else
dt.Rows.Add(currentRow.ToArray())
End If
Catch ex as Microsoft.VisualBasic.FileIO.MalformedLineException
Console.WriteLIne("Line " + ex.Message + " is not valid and will be skipped")
End Try
End While
End Using
return dt
End Function

oracle bulkcopy from vb.net databale

I am loading the CSV file to vb.net datatable .
then I am using Bulk copy command to write to database.
The problem is if one date cell in the data table is empty, i am receiving
ORA:-01840 input value not long enough for date format.
How to resolve this.
Public Class Form1
Dim cn As New OracleConnection("Data Source =(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST = ipaddressofserver)(PORT = portofserver))(CONNECT_DATA =(SERVER = DEDICATED)(SERVICE_NAME = oracleservicename)) ) ; User Id=useridofdb;Password=passwordofdb")
cn.Open()
MsgBox("connection opened")
Dim dt As DataTable = ReadCSV("D:\test.csv")
DataGridView1.DataSource = dt
Try
Dim _bulkCopy As New OracleBulkCopy(cn)
_bulkCopy.DestinationTableName = "TEST_TABLE"
_bulkCopy.BulkCopyTimeout = 10800
_bulkCopy.WriteToServer(dt)
cn.Close()
cn.Dispose()
cn = Nothing
MsgBox("Finished")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Function ReadCSV(ByVal path As String) As System.Data.DataTable
Try
Dim sr As New StreamReader(path)
Dim fullFileStr As String = sr.ReadToEnd()
sr.Close()
sr.Dispose()
Dim lines As String() = fullFileStr.Split(ControlChars.Lf)
Dim recs As New DataTable()
Dim sArr As String() = lines(0).Split(","c)
For Each s As String In sArr
recs.Columns.Add(New DataColumn())
Next
Dim row As DataRow
Dim finalLine As String = ""
For Each line As String In lines
row = recs.NewRow()
finalLine = line.Replace(Convert.ToString(ControlChars.Cr), "")
row.ItemArray = finalLine.Split(","c)
recs.Rows.Add(row)
Next
Return recs
Catch ex As Exception
Throw ex
End Try
End Function
End Class

Provider type could not be represented as a .NET type OracleTypeException

So I have an application that is writing to an oracle database, then another that is reading the data from the same database.
When I get to the line Dim msgTime As TimeSpan = reader.GetTimeSpan(2), I get an exception (see below).
The Oracle Documentation says that INTERVAL DAY TO SECOND (which is how I'm storing the data in the DB) can be converted to timespan (see here)
Does anyone know what causes this exception, and how to avoid it?
Thanks.
Exception:
Oracle.DataAccess.Types.OracleTypeException
Provider type could not be represented as a .NET type
at Oracle.DataAccess.Types.TimeSpanConv.GetTimeSpan(OpoITLValCtx* pValCtx, OracleDbType oraType)
at Oracle.DataAccess.Client.OracleDataReader.GetTimeSpan(Int32 i)
at MyProgram.pollDatabase(Object sender, DoWorkEventArgs e)
Write to DB code:
Dim oCommand As New OracleCommand("INSERT INTO LOGTABLE(PK, MID,MDATE,MTIME,STATUS,SEVERITY,ORIGQ,MESSAGE) VALUES (:pk, :msgid, :msgdate, :msgtime, :status, :severity, :message)")
oCommand.Parameters.Add("pk", OracleDbType.Varchar2, Guid.NewGuid().ToString().Substring(0, 12), ParameterDirection.Input)
oCommand.Parameters.Add("msgid", OracleDbType.Varchar2, message.MessageID, ParameterDirection.Input)
oCommand.Parameters.Add("msgdate", OracleDbType.Date, putDateSQL, ParameterDirection.Input)
oCommand.Parameters.Add("msgtime", OracleDbType.IntervalDS, putTimeSQL, ParameterDirection.Input)
oCommand.Parameters.Add("status", OracleDbType.Varchar2, "NEW", ParameterDirection.Input)
oCommand.Parameters.Add("severity", OracleDbType.Varchar2, messageSeverity, ParameterDirection.Input)
oCommand.Parameters.Add("message", OracleDbType.Clob, clob, ParameterDirection.Input)
Read from DB Code:
Dim conn As OracleConnection = New OracleConnection(oradb)
Dim oCommand As New OracleCommand("SELECT MID,MDATE,MTIME,STATUS,SEVERITY, ORIGQ, MESSAGE FROM LOGTABLE")
oCommand.CommandType = CommandType.Text
oCommand.Connection = conn
oCommand.Connection.Open()
Dim reader As Oracle.DataAccess.Client.OracleDataReader = oCommand.ExecuteReader()
If reader.HasRows Then
While reader.Read()
Try
Dim messageID As String = reader.GetString(0)
Dim msgDate As Date = reader.GetDateTime(1)
If Not reader.IsDBNull(2) Then
Dim msgTime As TimeSpan = reader.GetTimeSpan(2)
End If
Dim msgStatus As String = reader.GetString(3)
Dim msgSeverity As String = reader.GetString(4)
Dim msgOrigin As String = reader.GetString(5)
Dim msgContent As String = reader.GetString(6)
Catch ex As Exception
Console.Out.WriteLineAsync(ex.Message)
End Try
End While
End If
I needed to use Dim msgTimeInterval As Oracle.DataAccess.Types.OracleIntervalDS = reader.GetOracleIntervalDS(2) instead of Dim msgTime As TimeSpan = reader.GetTimeSpan(2)