Sorry for being newbie on this . But Im having an error when it comes to parsing part of my codes.Please help me. The version of my itextsharp is version 4.1.6
Unable to cast object of type 'iTextSharp.text.html.simpleparser.IncTable' to type 'iTextSharp.text.IElement'.
this is my vb codes:
Dim strHTMLContent As StringBuilder = New StringBuilder()
Dim strFinalHTML As String
Dim output = New MemoryStream()
Dim document = New iTextSharp.text.Document(PageSize.A4, 50, 50, 25, 25)
Dim dsRcpComp As New DataSet
Dim dtDetails As New DataTable
Dim RecipeName As String = ""
Dim RecipeIngredients As String = ""
dsRcpComp = GetRcpCompStandard(conStr, CodeListe, CodeTrans)
dtDetails = dsRcpComp.Tables(0)
RecipeName = Replace(dtDetails.Rows(0).Item("Name"), vbCr, "<br>")
RecipeIngredients = Replace(dtDetails.Rows(0).Item("Ingredients"), vbCr, "<br>")
strHTMLContent.Append("<table width=700 align='center' Border='0' cellspacing='50' fontsize='1' class='pdfFont'")
strHTMLContent.Append("<tr>")
'*** GERMAN COLUMN ***
strHTMLContent.Append("<td valign=top><table width=210 align='left'>")
strHTMLContent.Append("<tr><td><font size='2' >" & RecipeName & "</font></td></tr>")
strHTMLContent.Append("<tr><td></td></tr>")
strHTMLContent.Append("<tr><td>")
strHTMLContent.Append(RecipeIngredients & "<br><br>")
strHTMLContent.Append("</td></tr>")
strHTMLContent.Append("</tr></table>")
Dim styles As StyleSheet = New StyleSheet
styles.LoadStyle("pdfFont", "face", "courier")
strFinalHTML = Replace(strHTMLContent.ToString, "& ", "& ")
document.SetPageSize(iTextSharp.text.PageSize.A4.Rotate())
Dim parsedHtmlElements = HTMLWorker.ParseToList(New StringReader(strFinalHTML), styles)
Dim writer = PdfWriter.GetInstance(document, output)
document.Open()
For Each htmlElement In parsedHtmlElements
document.Add(TryCast(htmlElement, IElement))
Next
document.Close()
Return output
I'm getting the error in this line:
Dim parsedHtmlElements = HTMLWorker.ParseToList(New StringReader(strFinalHTML), styles)
Related
this is the code i have, dim sline from string to json, i have try it and search on google, but i havent done yet...
please help
Dim sURL As String
sURL = TextBox1.Text
Dim wrGETURL As WebRequest
wrGETURL = WebRequest.Create(sURL)
Dim myProxy As New WebProxy("myproxy", 80)
myProxy.BypassProxyOnLocal = True
wrGETURL.Proxy = myProxy
wrGETURL.Proxy = WebProxy.GetDefaultProxy()
Dim objStream As Stream
objStream = wrGETURL.GetResponse.GetResponseStream()
Dim objReader As New StreamReader(objStream)
Dim sLine As String = ""
Dim i As Integer = 0
Do While Not sLine Is Nothing
i += 1
sLine = objReader.ReadLine
If Not sLine Is Nothing Then
Console.WriteLine("{0}:{1}", i, sLine)
End If
Loop
Dim respon As Array = sLine.ToArray()
Console.ReadLine()
Console.WriteLine(respon("traceNo"))
Console.ReadLine()
i want to convert the Dim sline to json, how it possible?
Newtonsoft.JSON is a VERY handy NuGet to easy use JSON in VB.Net.
Seperate your lines into a List(Of Integer, String) (i,sLine)
and Serialize it with
Dim yourJSONString = JsonConvert.SerializeObject(yourList)
This is my code for read data from EXCEL file using ODBC driver and write in MySql Database.
Public Class WebForm3
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim MySqlCmd = New SqlCommand()
' Dim dialog As New System.Windows.Forms.OpenFileDialog()
'Dim dialog As New OpenFileDialog()
'dialog.Filter = "Excel files |*.xls;*.xlsx"
'dialog.InitialDirectory = "C:\"
'dialog.Title = "Select file for import"
'If dialog.ShowDialog() = DialogResult.OK Then
Try
Dim dt As DataTable
Dim buff0 As String
Dim buff1 As String
Dim buff2 As String
dt = ImportExceltoDatatable("C:\\Book1.xls")
For i = 0 To dt.Rows.Count - 1
buff0 = dt.Rows(i)(0)
buff1 = dt.Rows(i)(1)
buff2 = dt.Rows(i)(2)
Dim connStr As String = "server=localhost;user=root;database=ajaxsamples;port=3306;password=innoera;"
Dim connMysql As MySqlConnection = New MySqlConnection(connStr)
Dim sql As String = "INSERT INTO ajaxsamples.customers VALUES('" & buff0 & "','" & buff1 & "','" & buff2 & "')"
Dim cmd As MySqlCommand = New MySqlCommand(sql, connMysql)
cmd.ExecuteNonQuery()
cmd.Dispose()
connMysql.Close()
Next
Catch ex As Exception
MsgBox(Err.Description, MsgBoxStyle.Critical)
End Try
'End If
End Sub
Public Shared Function ImportExceltoDatatable(filepath As String) As DataTable
' string sqlquery= "Select * From [SheetName$] Where YourCondition";
Dim dt As New DataTable
Try
Dim ds As New DataSet()
Dim constring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & filepath & ";Extended Properties=""Excel 12.0;HDR=YES;"""
Dim con As New OleDbConnection(constring & "")
con.Open()
Dim myTableName = con.GetSchema("Tables").Rows(0)("TABLE_NAME")
Dim sqlquery As String = String.Format("SELECT * FROM [{0}]", myTableName)
'Dim myTableName = con.GetSchema("Tables").Rows(0)("TABLE_NAME")
'Dim sqlquery As String = String.Format("SELECT * FROM Sheet1$") ' "Select * From " & myTableName
Dim da As New OleDbDataAdapter(sqlquery, con)
da.Fill(ds)
dt = ds.Tables(0)
Return dt
Catch ex As Exception
MsgBox(Err.Description, MsgBoxStyle.Critical)
Return dt
End Try
End Function
End Class
I got this error,
"Connection must be valid and open "
whats wrong in code? I am newbie for VB. Any help would be appreciated.
You forgot to open your connection.
Try
connMysql = New MySqlConnection
connMysql.ConnectionString = connStr
connMysql.Open() 'You forgot to open your connection
sql = "SELECT * FROM users"
cmd = New MySqlCommand(sql, connMysql)
cmd.ExecuteNonQuery()
cmd.Dispose()
Catch ex As Exception
'your error code here
Finally
connMysql.Close() 'close your connection
End Try
Imports System.Data.Odbc
Imports System.Data.Sql
Imports System.Data.SqlClient
Imports MySql.Data
Imports MySql.Data.MySqlClient
Imports ADODB
.
.
.
Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Try
Dim conn As New OdbcConnection
Dim rset As New DataSet
Dim buff0 As String
Dim buff1 As String
Dim buff2 As String
Dim filePath As String = "C:\\Book3.xls"
conn.ConnectionString = "Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DriverId=790;Dbq=" & filePath & ";" 'Driver={Microsoft Excel Driver (*.xls)};DriverId=790;Dbq=d:\temp\test.xls;"
conn.Open()
rset.Open("select * from [Sheet1$]", conn, CursorTypeEnum.adOpenForwardOnly)
Do Until rset.EOF
buff0 = rset(0).Value
buff1 = rset(1).Value
buff2 = rset(2).Value
MySqlCmd = New MySqlCommand
MySqlCmd.Connection = Myconnect
MySqlCmd.CommandText = "INSERT INTO customers VALUES('" & buff0 & "','" & buff1 & "','" & buff2 & "')"
MySqlCmd.ExecuteNonQuery()
rset.MoveNext()
Loop
MsgBox("Import Successful!", MsgBoxStyle.Information, Title:="SOMS")
Catch ex As Exception
MsgBox("Import Unsuccessful!", MsgBoxStyle.Critical, Title:="SOMS")
End Try
End Sub
I am trying to import data from excel to mysql using this code got from web. But getting some errors. Give me suggestion where i am going wrong. I am very newbe for ADO,OLE. here i am using ODBC for reading data from excel and for insert I use mysql native driver. Another question is, Am i going in right direction or otherways possible?
Try this code and tell me :
Private Sub SimpleButton1_Click(sender As Object, e As EventArgs) Handles SimpleButton1.Click
Dim dialog As New OpenFileDialog()
dialog.Filter = "Excel files |*.xls;*.xlsx"
dialog.InitialDirectory = "C:\"
dialog.Title = "Select file for import"
If dialog.ShowDialog() = DialogResult.OK Then
Dim dt As DataTable
Dim buff0 As String
Dim buff1 As String
Dim buff2 As String
dt = ImportExceltoDatatable(dialog.FileName)
For i = 0 To dt.Rows.Count - 1
buff0 = dt.Rows(i)(0)
buff1 = dt.Rows(i)(1)
buff2 = dt.Rows(i)(2)
MySqlCmd = New MySqlCommand
MySqlCmd.Connection = Myconnect
MySqlCmd.CommandText = "INSERT INTO customers VALUES('" & buff0 & "','" & buff1 & "','" & buff2 & "')"
MySqlCmd.ExecuteNonQuery()
Next
End If
End Sub
Public Shared Function ImportExceltoDatatable(filepath As String) As DataTable
' string sqlquery= "Select * From [SheetName$] Where YourCondition";
Dim dt As New DataTable
Try
Dim ds As New DataSet()
Dim constring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & filepath & ";Extended Properties=""Excel 12.0;HDR=YES;"""
Dim con As New OleDbConnection(constring & "")
con.Open()
Dim myTableName = con.GetSchema("Tables").Rows(0)("TABLE_NAME")
Dim sqlquery As String = String.Format("SELECT * FROM [{0}]", myTableName) ' "Select * From " & myTableName
Dim da As New OleDbDataAdapter(sqlquery, con)
da.Fill(ds)
dt = ds.Tables(0)
Return dt
Catch ex As Exception
MsgBox(Err.Description, MsgBoxStyle.Critical)
Return dt
End Try
End Function
I use this script to get geocodes for any address in germany:
Public Function getGoogleMapsGeocode(sAddr As String) As String
Dim xhrRequest As XMLHTTP60
Dim sQuery As String
Dim domResponse As DOMDocument60
Dim ixnStatus As IXMLDOMNode
Dim ixnLat As IXMLDOMNode
Dim ixnLng As IXMLDOMNode
' Use the empty string to indicate failure
getGoogleMapsGeocode = ""
Set xhrRequest = New XMLHTTP60
sQuery = "http://maps.googleapis.com/maps/api/geocode/xml?sensor=false&address="
sQuery = sQuery & Replace(sAddr, " ", "+")
xhrRequest.Open "GET", sQuery, True
xhrRequest.send
Set domResponse = New DOMDocument60
domResponse.LoadXML xhrRequest.responseText
Set ixnStatus = domResponse.SelectSingleNode("//status")
If (ixnStatus.Text <> "OK") Then
'Exit Function
End If
Set ixnLat = domResponse.SelectSingleNode("/GeocodeResponse/result/geometry/location/lat")
Set ixnLng = domResponse.SelectSingleNode("/GeocodeResponse/result/geometry/location/lng")
getGoogleMapsGeocode = ixnLat.Text & ", " & ixnLng.Text
End Function
When I type the query string into the browser it returns a valid xml response with the geocodes. If I let vba do it, I get an error. Is there something I should know?
responseText :
"<?xml version="1.0" encoding="UTF-8"?>
<GeocodeResponse>
<status>INVALID_REQUEST</status>
</GeocodeResponse>
" : String : Modul8.getGoogleMapsGeocode
I having trouble deserializing this JSON.
The JSON looks like this:
{
"ticker": {
"high": 91.489,
"low": 88.3,
"avg": 89.8945,
"vol": 233637.9876,
"vol_cur": 2588.09448,
"last": 90.48,
"buy": 90.55,
"sell": 90.48,
"updated": 1372613806,
"server_time": 1372613807
}
}
And my function is this:
Private Function Btce(ByVal Address As String) As String
Dim rt As String = ""
Dim out As String
Dim wRequest As WebRequest
Dim wResponse As WebResponse
Dim SR As StreamReader
Dim Time As Date
Time = Now()
wRequest = WebRequest.Create(Address)
wResponse = wRequest.GetResponse
SR = New StreamReader(wResponse.GetResponseStream)
rt = SR.ReadToEnd
SR.Close()
Dim js As New System.Web.Script.Serialization.JavaScriptSerializer
Dim testObj = js.Deserialize(rt, New Object().GetType())
Dim high = testObj("High")
Dim low = testObj("Low")
Dim avg = testObj("Average")
Dim vol = testObj("Volume")
Dim last = testObj("Last")
Dim buy = testObj("Buy")
Dim sell = testObj("Sell")
out = "Data from btc-e.com" + Environment.NewLine
out += (Time) + Environment.NewLine
out += "High: " + Environment.NewLine
out += "Low: " + Environment.NewLine
out += "Average: " + Environment.NewLine
out += "Volume: " + Environment.NewLine
out += "Last: " + Environment.NewLine
out += "Buy: " + Environment.NewLine
out += "Sell: "
Return out
End Function
Then I get this in the console:
An unhandled exception of type 'System.Collections.Generic.KeyNotFoundException' occurred in Microsoft.VisualBasic.dll
Additional information: The given key was not present in the dictionary.
One of the problems is that you are looking for "Average" in testObj, but in the JSON it is "avg". And you are also looking for "Volume", not "vol".
In addition, the data returned by the deserialization is not a straight collection, it is a System.Collections.Dictionary(Of String, Object) where there is one entry for each of the representing the ticker objects in the json.
Each ticker object contains a String Key and a Value where Value is a System.Collections.Generic.KeyValuePair, which is case-sensitive. Value contains the collection of data (i.e. "high", 9.4189).
Based on this, your code should look like:
Dim js As New System.Web.Script.Serialization.JavaScriptSerializer
Dim cObjects = js.Deserialize(rt, New Object().GetType())
Dim counter As Integer
Dim out As New System.Text.StringBuilder(1000)
' Use a stringbuilder to capture the output; much more efficient than constant string concat
out.Append("Data from btc-e.com").AppendLine()
For Each testObj In cObjects
Dim high = testObj.Value("high")
Dim low = testObj.Value("low")
Dim avg = testObj.Value("avg")
Dim vol = testObj.Value("vol")
Dim last = testObj.Value("last")
Dim buy = testObj.Value("buy")
Dim sell = testObj.Value("sell")
' Since you will be processing multiple records, show something
' in the output about where you are
counter += 1
out.Append("Element ").Append(counter).AppendLine()
out.Append(DateTime.Now).AppendLine()
out.Append("High: ").Append(high).AppendLine()
out.Append("Low: ").Append(low).AppendLine()
out.Append("Average: ").Append(avg).AppendLine()
out.Append("Volume: ").Append(vol).AppendLine()
out.Append("Last: ").Append(last).AppendLine()
out.Append("Buy: ").Append(buy).AppendLine()
out.Append("Sell: ").Append(sell).AppendLine()
Next
Return out.ToString()
When deserializing to an object graph, you can just use DeserializeObject
The keys you are looking for are not present under the object you've just deserialized, but are in fact keys of the object under "ticker".
The default equality comparer used for dictionaries is probably case sensitive. You might want to construct a new dictionary while explicitly specifying StringComparer.***IgnoreCase, where *** is any of Ordinal, InvariantCulture or CurrentCulture.
For example:
Dim testObj = js.Deserialize(Of Dictionary(Of String, Dictionary(Of String, Single)))(rt)("ticker")
testObj = New Dictionary(Of String, Single)(testObj, StringComparer.InvariantCultureIgnoreCase)
Dim high = testObj("High")