I have a simple VB.Net program for saving webpages as mht format
currently I'm using the following way:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
WebBrowser1.Navigate("http://www.google.com")
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim SaveFileDialog1 As New SaveFileDialog()
SaveFileDialog1.Filter = "mht files (*.mht)|*.mht|All files (*.*)|*.*"
If SaveFileDialog1.ShowDialog() = DialogResult.OK Then
fileNamePath = SaveFileDialog1.FileName
SavePage(WebBrowser1.Url.ToString, fileNamePath)
End If
End Sub
Private Sub SavePage(ByVal Url As String, ByVal FilePath As String)
Dim iMessage As CDO.Message = New CDO.Message
iMessage.CreateMHTMLBody(Url, CDO.CdoMHTMLFlags.cdoSuppressObjects, "", "")
Dim adodbstream As ADODB.Stream = New ADODB.Stream
adodbstream.Type = ADODB.StreamTypeEnum.adTypeText
adodbstream.Charset = "UTF-8"
adodbstream.Open()
iMessage.DataSource.SaveToObject(adodbstream, "_Stream")
adodbstream.SaveToFile(FilePath, ADODB.SaveOptionsEnum.adSaveCreateOverWrite)
End Sub
My code work fine, but the save process is like a normal save page in a browser. Right-Click > Save page as ... and select a direction with a name for saving file
Is there a way that save operation to be performed automatically? without any popup windows, just give the program a direction and a file name in the code
for example :
SavePage("http://google.com", "C:\google.mht")
this code didn't work and i have error Write to file failed. for the following code
adodbstream.SaveToFile(FilePath, ADODB.SaveOptionsEnum.adSaveCreateOverWrite)
Imports ADODB
Imports CDO
Public Class Form1
Dim fileNamePath = "C:\"
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button1.Click
WebBrowser1.Navigate(TextBox1.Text)
End Sub
Private Sub SavePage(ByVal Url As String, ByVal FilePath As String)
Try
Dim iMessage As CDO.Message = New CDO.Message
iMessage.CreateMHTMLBody(Url, CDO.CdoMHTMLFlags.cdoSuppressObjects, "", "")
Dim adodbstream As ADODB.Stream = New ADODB.Stream
adodbstream.Type = ADODB.StreamTypeEnum.adTypeText
adodbstream.Charset = "UTF-8"
adodbstream.Open()
iMessage.DataSource.SaveToObject(adodbstream, "_Stream")
adodbstream.SaveToFile(FilePath & CheckAndClean(TextBox1.Text) & ".mht", ADODB.SaveOptionsEnum.adSaveCreateOverWrite)
Catch ex As Exception
End Try
End Sub
Private Function CheckAndClean(ByVal StringToCheck As String) As String
Dim sIllegal As String = "\,/,:,*,?," & Chr(34) & ",<,>,|"
Dim arIllegal() As String = Split(sIllegal, ",")
Dim sReturn As String
sReturn = StringToCheck
For i = 0 To arIllegal.Length - 1
sReturn = Replace(sReturn, arIllegal(i), "")
Next
Return sReturn
End Function
Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
SavePage(TextBox1.Text, fileNamePath)
End Sub
Try:
adodbstream.SaveToFile(FilePath & "Filename.mht", ADODB.SaveOptionsEnum.adSaveCreateOverWrite)
Related
I have the code written to connect to the ODBC registry.
The database name is written to the combobox.
I need to transfer my ip address and password from ODBC.ini to the connect string after selecting the database from the combobox.
This is a connection to MYSQL.
Thank you
Private Sub DsnLookup()
Dim dsnNames As New List(Of String)
Dim reg As Microsoft.Win32.RegistryKey = Registry.CurrentUser.OpenSubKey("Software")
If reg IsNot Nothing Then
reg = reg.OpenSubKey("ODBC")
If reg IsNot Nothing Then
reg = reg.OpenSubKey("ODBC.INI")
If reg IsNot Nothing Then
For Each dsn As String In reg.GetSubKeyNames
dsnNames.Add(dsn)
Next
End If
End If
End If
For Each Name As String In dsnNames
ComboBox1.Items.Add(Name)
Next Name
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DsnLookup()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connString As String = "Database='combobox data;Data Source='ip adres odbc;" _
& "User Id=root;Password=' odbc PWD"
You can get the Server Name (or IP) and Database name from the ODBC.INI but it doesn't store the password. Either include a master password in your connectionstring (securely of course) or look into other authentication options.
This is how to get the Database and Server info from the registry. Keeping your code the same, but replacing the Button1.Click event and adding an additional function:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If ComboBox1.SelectedIndex >= 0 Then 'Make sure something from dropdown selected
Dim connString As String = String.Format("Database='{0}';Data Source='{1}';User Id=root;", GetODBCValue(ComboBox1.SelectedItem, "Database"), GetODBCValue(ComboBox1.SelectedItem, "Server"))
End If
End Sub
Private Function GetODBCValue(ByVal ODBCName As String, ByVal ValueName As String) As String
Dim reg As Microsoft.Win32.RegistryKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software")
reg = reg.OpenSubKey("ODBC")
reg = reg.OpenSubKey("ODBC.INI")
reg = reg.OpenSubKey(ODBCName)
Return reg.GetValue(ValueName)
End Function
thank you for the answer
I tried to edit it
Private Function GetODBCValu(ByVal ODBCName As String, ByVal ValueName As String) As String
Dim dsnNames As New List(Of String)
Dim reg As Microsoft.Win32.RegistryKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software")
reg = reg.OpenSubKey("ODBC")
reg = reg.OpenSubKey("ODBC.INI")
reg = reg.OpenSubKey(ODBCName)
Return reg.GetValue(ValueName)
For Each dsn As String In reg.GetSubKeyNames
dsnNames.Add(dsn)
Next
For Each Name As String In dsnNames
ComboBox1.Items.Add(Name)
Next Name
End Function
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim connString As String = String.Format("Database='{0}';Data Source='{1}';User Id=root;", GetODBCValu(ComboBox1.SelectedItem, "Database"), GetODBCValu(ComboBox1.SelectedItem, "Server"))
Dim conn As New MySqlConnection(connString)
Dim cmd As New MySqlCommand()
Try
Call conecDB()
dt = New DataTable 's_table
Dim con As New SqlConnection
DateTimePicker1.CustomFormat = "yyyy-MM-dd"
DateTimePicker1.Format = DateTimePickerFormat.Custom
DateTimePicker2.CustomFormat = "yyyy-MM-dd"
DateTimePicker2.Format = DateTimePickerFormat.Custom
conn.Open()
cmd.Connection = conn
da = New MySql.Data.MySqlClient.MySqlDataAdapter("select --- ", connDB)
comBuilderDB = New MySql.Data.MySqlClient.MySqlCommandBuilder(da)
da.Fill(dt)
dbvypis.DataSource = dt
conn.Close()
MessageBox.Show("COMPLET")
Catch ex As MySqlException
Console.WriteLine("Error: " & ex.ToString())
End Try
Try
'declaring variable as integer to store the value of the total rows in the datagridview
Dim max As Integer = dbvypis.Rows.Count - 1
Dim total As String = "TOTAL ----->"
Dim TOTALCOST As Integer = 0
'getting the values of a specific rows
For Each row As DataGridViewRow In dbvypis.Rows
'formula for adding the values in the rows
TOTALCOST += row.Cells(1).Value
Next
dbvypis.Rows(max).Cells(1).Value += TOTALCOST
dbvypis.Rows(max).Cells(0).Value = total
Catch ex As Exception
MsgBox(ex.Message)
End Try
It occurred to me that if I select a database in the comboboxu so it gets into ODBC and connString to the command adds the server and database name
Then it writes to me in the result Index is out of range, Index must be non-negative and must be smaller than the collection size. Parameter name: index
I have a problem regarding producing report but before that I need to run a code in order for me to create multiple conditions for the next report.
I have here a screenshot of my tbldtr. What I want is the value of am_time_in which has the data type of time will be transferred into a label/textbox/variable. I am using Visual Basic with MySQL.
Here is my code
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
checktime()
End Sub
Private Sub checktime()
Dim cn As New MySqlConnection(CnPath)
Dim Sql As String = "SELECT `tbldtr`.`am_time_in` FROM `tbldtr` WHERE `tbldtr`.`id` = '11' AND `tbldtr`.`dtrdate` = '2017-10-16'"
Dim daCmd5 As New MySqlCommand(Sql, cn)
cn.Open()
Dim datinfo As MySqlDataReader = daCmd5.ExecuteReader()
While datinfo.Read()
If IsDBNull(datinfo(0)) = True Then
lblamtimein.Text = ""
Else
lblamtimein.Text = datinfo(0)
End If
End While
cn.Close()
End Sub
End Class
Error here:
The error is occurring on this line -
lblamtimein.Text = datinfo(0)
A timespan needs to be explicitly converted to a string like this -
lblamtimein.Text = datinfo(0).ToString
Im doing a webform in vb.net I'm consuming a webservice, Which returns me to all the countries
Only have 1 button Enviar that calls the countries.
Imports service_country = WebServiceVB2.country
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim serv_country As New service_country.country '--Create object'
Dim MyDoc As New System.Xml.XmlDocument
Dim MyXml As String = serv_country.GetCountries() '--Execute procedure from webservice'
MyDoc.LoadXml(MyXml) '--Read Myxml and convert to XML'
Dim SymbolText As String = MyDoc.SelectSingleNode("//NewDataSet/Table/Name").InnerText '--select the node'
Label1.Text = SymbolText
End Sub
My question is How can I select all the values that are inside the 'name'.
Actually it only shows one.
For Example:
Thanks in advance.
This was an interesting problem. Since data is coming as a webpage the open bracket was coming as "& l t ;" while the closing bracket was coming as "& g t ;". So these had to be replaced. I used xml linq to get the names :
Imports System.Xml
Imports System.Xml.Linq
Module Module1
Const URL As String = "http://www.webservicex.net/country.asmx/GetCountries"
Sub Main()
Dim doc1 As XDocument = XDocument.Load(URL)
Dim docStr As String = doc1.ToString()
docStr = docStr.Replace(">", ">")
docStr = docStr.Replace("<", "<")
Dim doc2 As XDocument = XDocument.Parse(docStr)
Dim root As XElement = doc2.Root
Dim defaultNs As XNamespace = root.GetDefaultNamespace()
Dim names() As String = doc2.Descendants(defaultNs + "Name").Select(Function(x) CType(x, String)).ToArray()
End Sub
End Module
Using WebUtility
Imports System.Xml
Imports System.Xml.Linq
Imports System.Text
Imports System.Net
Module Module1
Const URL As String = "http://www.webservicex.net/country.asmx/GetCountries"
Sub Main()
Dim xReader As XmlReader = XmlTextReader.Create(URL)
xReader.MoveToContent()
Dim doc As XDocument = XDocument.Parse(WebUtility.HtmlDecode("<?xml version=""1.0"" encoding=""iso-8859-9"" ?>" & xReader.ReadOuterXml))
Dim root As XElement = doc.Root
Dim defaultNs As XNamespace = root.GetDefaultNamespace()
Dim names() As String = doc.Descendants(defaultNs + "Name").Select(Function(x) CType(x, String)).ToArray()
End Sub
End Module
When my form for creating a group of students loads up, I receive a NullReferenceException for seemingly no reason. This is the code that handles the form loading:
Private Sub AddGroupForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
For i As Integer = 0 To Form1.lstStudents.Items.Count - 1
lstStudentList.Items.Add(Form1.lstStudents.Items.Item(i))
Next
tempStudentList.AddRange(Form1.mainStudentList)
btnAllOut.Enabled = False
btnOneOut.Enabled = False
End Sub
The mainStudentList referred to is a list that is populated upon loading by using MySQL:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
Dim conn As New MySqlConnection("server=localhost;user=root;database=new_project;port=3306;password=********;")
conn.Open()
Dim command As New MySqlCommand("SELECT * FROM students WHERE deleted=0 ORDER BY lastName;", conn)
Dim dataSet As New DataSet()
Dim dataAdapter As New MySqlDataAdapter()
dataAdapter.SelectCommand = command
dataAdapter.Fill(dataSet, "students")
Dim dataTable As DataTable = dataSet.Tables("students")
For Each row As DataRow In dataTable.Rows
Dim newStudent As New Student
newStudent.intIDNum = row.Item("passCode")
newStudent.strFirstName = row.Item("firstName")
newStudent.strLastName = row.Item("lastName")
newStudent.chrGender = row.Item("gender")
newStudent.dateDOB = row.Item("dateOfBirth")
newStudent.intAge = CInt(Today.Year - newStudent.dateDOB.Year)
newStudent.intYearGroup = row.Item("yearGroup")
newStudent.intSkillLevel = SByte.Parse(row.Item("skillLevel"))
mainStudentList.Add(newStudent)
lstStudents.Items.Add(newStudent.nameConcat(newStudent.strFirstName, newStudent.strLastName))
Next
conn.Close()
Catch ex As Exception
MsgBox("Error: " & ex.ToString())
End Try
End Sub
The specific exception occurs when the tempStudentList attempts to load the values in the mainStudentList. Specifically, it states that "Object reference not set to instance of an Object".
Make sure mainStudentList has been initialized first.
c#
List<Student> mainStudentList = new List<Student>();
VB.Net
Dim mainStudentList As New List(Of Student)()
i am trying to fetch some data from Url using Httpwebrequest/response, i am getting response which i am showing in a msgbox. It show whole HTML contents.
Now my i want to fetch a specific tag(TD tag) value and show all its value in a combobox in vb.net desktop application.
my code to get response from webserver is :
enter code here
Imports System.IO
Imports System.Net
Imports System.Xml
Imports System.Text.Encoder
Public Class login
Private Sub login_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
End
End Sub
Private Sub Panel1_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Panel1.Paint
End Sub
Private Sub Ok_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Ok.Click
Dim strId As String = txt_uid.Text
Dim strPwd As String = txt_pwd.Text
Dim oEncoder As New System.Text.ASCIIEncoding
Dim postData As String = "UM_username=" + strId
postData += ("&UM_password=" + strPwd)
Dim data As Byte() = oEncoder.GetBytes(postData)
MsgBox(postData)
Dim webStream As Stream
Dim webResponse As String = ""
Dim req As HttpWebRequest
Dim res As HttpWebResponse
Dim Output As String
'Dim Posit1 As Int32
'Dim Posit2 As Int32
req = WebRequest.Create("http://localhost/basic_framework/index.php?menu=login&UM_email=" & strId & "&UM_password=" & strPwd)
req.ContentType = "application/x-www-form-urlencoded"
req.KeepAlive = False
req.Method = "POST"
res = req.GetResponse()
webStream = res.GetResponseStream()
Dim webStreamReader As New StreamReader(webStream)
While webStreamReader.Peek >= 0
Output = webStreamReader.ReadToEnd()
RichTextBox1.Text = Output
Msgbox(Output)
End While
End Sub
End Class
this code get the response from url and show it in a richtextbox or msgbox
Now i want to get a specific tag value (say, td, option values) and show it in a combobox in my vb.net application form dynamically.It would be needed to parse html content then get that tag value . Please suggest me a way......
If parsing needed , how to parse html contents to get only specific tag value in a combobox in vb.net form
Well...if you can be sure that your request returns valid XHTML (which is XML indeed), you might be able to use an XPath expression.
For the most complicated cases (e.g., an AJAX web-site, etc.) you could use HTMLUnit library with iKVM.