Visual Basic code
Declare array of size[1]Edit
Dim a As String() = New String(4) {}
Write to log (textbox on form) with autoscrollEdit
'writes a line to a TB that should be setup to have a monospace font like courier new
Sub WriteToLog(t As String) 'takes argument for string
LogTB.AppendText(t & vbCrLf) 'writes a line of text and a CR to the LogTB
End Sub
'writes lines to a TB that should be setup to have a monospace font like courier new
Sub WriteSeparatorToLog(t As String, s As Integer) 'takes argument for string and int for separator
Dim logll As Integer = 72 'set the line length
Dim sep As String = "-" 'default separator
Select Case s '}
Case 0 '}
sep = "-" '}
Case 1 '}
sep = "=" '} set the separator
Case 2 '}
sep = "#" '}
Case 3 '}
sep = "*" '}
End Select '}
If t.Length > 0 Then 'if text is supplied then create the log line
Dim tot As Integer = t.Length 'calculate total characters
Dim es = Math.Floor((logll - tot) / 2) 'calculate half line length
For i = 0 To es - 1 '}
LogTB.AppendText(sep) '} write separator characters
Next '}
LogTB.AppendText(" " & t & " ") 'write the text
For i = 0 To (logll - es - t.Length) '}
LogTB.AppendText(sep) '} write the other separator characters
Next '}
LogTB.AppendText(vbCrLf) 'insert line break
Else 'if no text is supplied then create a line only
For i = 0 To (logll + 2) '}
LogTB.AppendText(sep) '} write the separator line with no text
Next '}
LogTB.AppendText(vbCrLf) 'insert line break
End If
End Sub
'autoscrolls the log window
Private Sub LogTB_TextChanged_1(sender As Object, e As EventArgs) Handles LogTB.TextChanged
LogTB.SuspendLayout() 'stop updates
LogTB.SelectionStart = LogTB.TextLength 'select text
LogTB.ScrollToCaret() 'position the scrollbar at the end of selection
LogTB.ResumeLayout() 'start updates again
End SubPlace a textbox called LogTB on the form.
Collections vs Dictionaries[2]Edit
Feature | COLLECTION | DICTIONARY | Remark
------------------------+------------+------------+--------------------------------
Usually faster | | X |
------------------------+------------+------------+--------------------------------
Supported by VB Script | | X | Collections do not exist in VBS.
------------------------+------------+------------+--------------------------------
| | | Dicts: Add ref to Miscrosoft
Native to VBA | X | | Scripting Library. Usage:
| | | Dim MyDict As Scripting.Dictionary
| | | Set MyDict = New Scripting.Dictionary
------------------------+------------+------------+--------------------------------
Can change Keys and | | | Dict properties are writable.
Items | | X | For collections, remove the item
| | | and add a new item.
------------------------+------------+------------+--------------------------------
| | | A collection enumerates its items:
| | | For Each x In MyCollection
| | | Debug.Print x
Enumerated | X | X | Next x
| | | A dict enumerates its keys:
| | | For Each x In MyDictionary
| | | Debug.Print MyDictionary.Item(x)
| | | Next x
------------------------+------------+------------+--------------------------------
| | | A 1-d array of keys
Directly output to | | | and items can be returned by
array | | X | dict methods .Keys and .Items.
| | | (The array is zero-based even
| | | with Option Base 1.)
------------------------+------------+------------+--------------------------------
Retrieve and access | X | X |
items | | |
------------------------+------------+------------+--------------------------------
Add items | X | X |
------------------------+------------+------------+--------------------------------
Implicitly add items | | X | Dicts can implicitly add items
| | | using .Item property.
------------------------+------------+------------+--------------------------------
Remove items | X | X |
------------------------+------------+------------+--------------------------------
Remove all items in | | | With collections, each item must
one step | | X | be removed in turn, or the
| | | collection destroyed and recreated.
------------------------+------------+------------+--------------------------------
Count items | X | X |
------------------------+------------+------------+--------------------------------
Return item using key | X | X |
as lookup value | | |
------------------------+------------+------------+--------------------------------
Return item using | | |
ordinal position | X | (Slow) |
as lookup value | | |
------------------------+------------+------------+--------------------------------
Return ordinal | | |
position using item | X | ?? |
as lookup value | | |
------------------------+------------+------------+--------------------------------
Retrieve and access | | X | Collection keys only used to
keys | | | look up data, not retrievable.
------------------------+------------+------------+--------------------------------
Keys optional | X | | Big + of collections, assuming keys
| | | are not needed. (Access via index.)
------------------------+------------+------------+--------------------------------
Case sensitivity | | X |
optional | | |
------------------------+------------+------------+--------------------------------
| | | Collection keys must be strings.
Keys can be any type | | X | Dict keys can have any type
| | | (except arrays), incl. mixed types.
------------------------+------------+------------+--------------------------------
Keys must be unique | X | X |
------------------------+------------+------------+--------------------------------
| | | * For collections, add code:
| | | Public Function _
| | | Contains(col As Collection, _
Supports .Exists method | Remark* | X | key As Variant) As Boolean
| | | On Error Resume Next
| | | col(key)
| | | Contains = (Err.Number = 0)
------------------------+------------+------------+--------------------------------
Preserve key order when | | X | This is because collection keys
sorting by item value | | | are write-only, not read. Poor design!
Regex MatchEdit
Public Sub Main()
Dim pattern As String = "\ba\w*\b"
Dim input As String = "An extraordinary day dawns with each new day."
Dim m As Match = Regex.Match(input, pattern, RegexOptions.IgnoreCase)
If m.Success Then
Console.WriteLine("Found '{0}' at position {1}.", m.Value, m.Index)
End If
End Sub
Regex CalculatorEdit
Generic error handling with error detailsEdit
Try
'try this code for size....
Catch ex As Exception
MessageBox.Show(ex.Message) 'show the specific error
End Try
Search pdf for textEdit
(based on[3])Edit
'function to searh a pdf for a string. returns a list of integers that are page numbers of the found string
Public Shared Function GetTextFromPDF(ByVal PdfFileName As String, searchPhrase As String) As List(Of Integer)
Dim fpage As New List(Of Integer)
Try
Dim oReader As New iTextSharp.text.pdf.PdfReader(PdfFileName)
Dim sOut = ""
For i = 1 To oReader.NumberOfPages
Dim its As New iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy
sOut = iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(oReader, i, its)
Dim adrRx As Regex = New Regex(searchPhrase)
For Each item As Match In adrRx.Matches(sOut)
fpage.Add(i)
Next
Next
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Dim ddup As List(Of Integer)
ddup = fpage.Distinct().ToList
Return ddup
End Function
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim ret As List(Of Integer) = GetTextFromPDF("C:\Users\david.lowe\Documents\NXOpen_Getting_Started.pdf", "drawings")
If ret.Count > 0 Then
Dim t = ""
For j = 0 To ret.Count - 1
t &= ret(j).ToString & vbCrLf
Next
MsgBox("found the term on pages" & vbCrLf & t)
Else
MsgBox("nothing found")
End If
End Sub
Webview2 (updated internal webbrowser)Edit
Instructions to setup[4]
End of textbox edit (lostfocus)Edit
Use lostfocus event[5]
Get appdata writable locationEdit
Imports System.Environment Imports System.IO ReadOnly appData As String = GetFolderPath(SpecialFolder.ApplicationData) ReadOnly savefile As String = appData & "\" & "nxsearchlist.txt"
Check if a file existsEdit
If File.Exists(filepath) Then
'execute if exists code
Else
'execute if does not exist
End If
Read a text file to a textboxEdit
Sub Readin(mems As Stream)
dxfTB.Visible = False : dxfTB.Enabled = False
Using r As New StreamReader(mems)
dxfTB.Text = r.ReadToEnd
End Using
dxfTB.Visible = True : dxfTB.Enabled = True
End Sub
Write a text file from a textboxEdit
'save file function
Sub WriteOut()
File.WriteAllText(savefile, sourcesListTB.Text)
End Sub
Regions to enclose code blocks[6]Edit
#Region "RegionName"
'Code in region goes here.
#End Region
Object type routines[7]Edit
'function that takes any object and returns the object type
Function WhatObject(ByVal Obj As Object)
Return Obj.GetType()
End Function
'function that takes any object and returns true if it is a string
Function IsObjectAString(ByVal Obj As Object)
If Obj.GetType() Is GetType(String) Then
Return True
Else
Return False
End If
End Function
'function that takes any object and returns true if it is a double
Function IsObjectADouble(ByVal Obj As Object)
If Obj.GetType() Is GetType(Double) Then
Return True
Else
Return False
End If
End Function
Exit an application[8]Edit
Application.Exit()
Open file dialog exampleEdit
With path and filename parsing from the selected file.
Dim inputfile, outputpath, outputfilename
OpenFileDialog1.Filter = "Text files | *.txt"
If OpenFileDialog1.ShowDialog = DialogResult.OK Then
inputfile = OpenFileDialog1.FileNames(0)
outputfilename = Path.GetFileNameWithoutExtension(inputfile)
outputpath = Path.GetDirectoryName(inputfile)
MessageBox.Show("The path is " & outputpath & vbCrLf & "The filename will begin with " & outputfilename)
End If
Get files in directory recursivelyEdit
Dim FileNames = IO.Directory.GetFiles("c:\path", "*.*", IO.SearchOption.AllDirectories)
Get files in a directory (no recursion)Edit
Dim FileNames() As String = IO.Directory.GetFiles("c:\path")
Parsing filenames and paths[9]Edit
Dim filename = Path.GetFileNameWithoutExtension(file) 'get the filename part only from the complete path Dim extension = Path.GetExtension(file) 'get the file extension part only from the complete path
Send an emailEdit
'create the mail message
Dim mail As New MailMessage()
'set the addresses
mail.From = New MailAddress("xx@xx")
mail.[To].Add("xx@xx")
'set the content
mail.Subject = "This is an email"
mail.Body = "this is a sample body"
'set the server
Dim smtp As New SmtpClient("localhost")
'send the message
Try
smtp.Send(mail)
Response.Write("Your Email has been sent sucessfully - Thank You")
Catch exc As Exception
Response.Write("Send failure: " & exc.ToString())
End Try
Timer exampleEdit
Define the clock interval with
Timer1.Interval = 213
Timer1.Start()
The tick block is executed each interval
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
'sendCommand("<nowiki>http://192.168.1.201:9001/</nowiki>", "On15")
Button10.PerformClick()
End Sub
Timer example (one shot)Edit
'start timer in whatever method...
Timer1.Start()
'Timer to handle tick event
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Timer1.Stop()
'...do one shot operations here
End Sub
Random number exampleEdit
' Initialize the random-number generator. Randomize() ' Generate random value between 1 and 6. Dim value As Integer = CInt(Int((6 * Rnd()) + 1))
Proper random function that correctly deals with .next and seedingEdit
'Handy random number genertion function with .next / proper seeding support
Public Function GetRandom(ByVal Min As Integer, ByVal Max As Integer) As Integer
Static Generator As System.Random = New System.Random()
Return Generator.Next(Min, Max)
End Function
Can also be used to select more than one file and thus returns an array of filenames:Edit
OpenFileDialog1.Filter = "TEXT FILE | *.txt |PDF FILE |.pdf |ALL FILES |*.*" If OpenFileDialog1.ShowDialog = DialogResult.OK Then For x = 0 To OpenFileDialog1.FileNames.Count - 1 MsgBox(OpenFileDialog1.FileNames(x)) Next End If
Must set multiple select to true in the property explorer
Background workerEdit
'Load page data into datatable button
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
BackgroundWorker1.RunWorkerAsync()
End Sub
'Load page data into datatable sub
Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim counter As String = ""
Dim i = 0
Do While i < 50000
Try
counter = System.IO.File.ReadLines("c:\temp\output.txt")(i)
Dim R As DataRow = dt.NewRow
R("Title") = Split(counter, vbTab)(0)
R("Timestamp") = Split(counter, vbTab)(1)
R("SHA1") = Split(counter, vbTab)(2)
dt.Rows.Add(R)
i = i + 1
Catch
Exit Do
End Try
Loop
DataGridView1.Invoke(Sub() redrawdgv())
End Sub
Background worker and argument passing and progress update (preferred)Edit
Place a progressBar, button and label on a form
Option Strict On
Option Explicit On
Imports System.ComponentModel
Public Class Form1
'˅˅˅˅˅˅˅˅ MAIN THREAD ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
'trigger the bgw. this is the entry point in the main code from where you initiate the bgw things
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
BackgroundWorker1.RunWorkerAsync() '<-- do the call in yout main code using this line like this
'other stuff can be called here while the bgw is running
End Sub
'this is a helper sub to coordinate the various handlers for progress etc. the actual worker is called from here with arguments for the bgw if necessary
Private Sub BackgroundWorker1_DoWork_1(sender As Object, e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork
BGWprocess(BackgroundWorker1, "Some string", "Some other string") 'two (or none or many) arguments may be passed to the bgw
End Sub
'update main ui thread with progress updates
Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
ProgressBar1.Visible = True
ProgressBar1.Value = e.ProgressPercentage 'two parameters may be passed from the worker.reportprogress method: .ProgressPercentage - which is a built-in variable
Label1.Text = e.UserState.ToString 'and also a .UserState parameter (optional) which can be whatever you define it as (in this case a string)
If ProgressBar1.Value = 100 Then
ProgressBar1.Visible = False
End If
End Sub
'˄˄˄˄˄˄ MAIN THREAD ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
'˅˅˅˅˅˅ OTHER THREAD ###################################################################################################################################################
'this is the bgw worker thread sub. the calling arguments from dowork are received here ie: MsgBox(Var1 & Var2)
Sub BGWprocess(worker As System.ComponentModel.BackgroundWorker, Var1 As String, Var2 As String)
worker.WorkerReportsProgress = True 'it is False by default
For i = 1 To 100 '}
Threading.Thread.Sleep(10) '} this is the background work stuff where you do useful work
worker.ReportProgress(i, i.ToString()) '} <-- this line sends the two progress arguments that .ProgressChanged (above) is able to utilise
Next i '}
End Sub
'˄˄˄˄˄˄ OTHER THREAD ###################################################################################################################################################
End Class
Read file buffer of file size length or max size 1GB*Edit
*Note that if the file is larger, only 1GB will be read into the buffer with this method. It is quick and dirty. The max size can be altered to suit the application. There is some maximum but it is unknown.
Private Function GetMemStreamFromFile_BestEverFunctionName(ByVal FilePath As String) As IO.MemoryStream
Dim stFile As IO.Stream = IO.File.Open(FilePath, IO.FileMode.Open)
Dim bs
Try
bs = CInt(stFile.Length)
Catch
bs = 1000000000
End Try
Dim stMem As IO.MemoryStream = New IO.MemoryStream
Dim buffer(bs) As Byte
stFile.Read(buffer, 0, buffer.Length)
stMem.Write(buffer, 0, buffer.Length)
stFile.Close()
stMem.Seek(0, IO.SeekOrigin.Begin)
Return stMem
End Function
Date and TimeEdit
Dim StartTime As DateTime = #6/12/2008 3:09:00 PM# Dim EndTime As DateTime = #6/10/2008 12:04:00 PM# Dim TimeDiff As TimeSpan = EndTime.Subtract(StartTime) Dim Days As Integer = TimeDiff.ToatlDays 'calculate Value of Days Component Dim Minutes As Integer = TimeDiff.TotalMinutes 'calculate Value of Minutes Component Dim Seconds As Integer = TimeDiff.TotalSeconds 'calculate Value of Seconds Component Dim TotalDays As Integer = TimeDiff.TotalDays 'calculate Value of Total Days Dim TotalHours As Integer = TimeDiff.TotalHours 'calculate Value of Total Minutes Dim TotalSeconds As Integer = TimeDiff.TotalSeconds 'calculate Value of Total Seconds
Count the number of linesEdit
Dim lineCount = File.ReadAllLines(inputfile).Length
Database tutorialEdit
Microsoft docs[10]
SQLiteEdit
Imports System.Data.SQLite
Imports System.Text
Public Class Form1
Dim sqlite_mem As SQLiteConnection
Dim dataSources As String
Dim createString = "CREATE TABLE IF NOT EXISTS test (ip1 INTEGER, ip2 INTEGER, ip3 INTEGER, ip4 INTEGER, text varchar(24));"
Dim diskContents
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'run sub to create the memory DB instance
memDBConnect()
'create and execute the command to create the memory DB table
Dim sqlite_cmd = sqlite_mem.CreateCommand()
sqlite_cmd.CommandText = createString
sqlite_cmd.ExecuteNonQuery()
End Sub
'create the memory DB instance
Sub memDBConnect()
Dim memDBsource = "Data Source=:memory:;Version=3;"
sqlite_mem = New SQLiteConnection(memDBsource)
sqlite_mem.Open()
End Sub
'destroy the memory DB instance
Sub memDBDisconnect()
Try
If sqlite_mem IsNot Nothing Then sqlite_mem.Close()
Catch ex As Exception
End Try
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim sqlite_cmd = sqlite_mem.CreateCommand()
' Let the SQLiteCommand object know our SQL-Query:
Dim id = TextBox1.Text
sqlite_cmd.CommandText = "INSERT INTO test (ip1, ip2, ip3, ip4, text) VALUES (81, 174, 250, 136, 'FFFFFFFFFFFFFFFFFFFFFFFF');"
Try
sqlite_cmd.ExecuteNonQuery()
Catch
MsgBox("Nope")
End Try
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
OutputTextBox.Enabled = False
OutputTextBox.Visible = False
Dim sqlite_cmd = sqlite_mem.CreateCommand()
Dim sqlite_datareader As SQLiteDataReader
sqlite_cmd.CommandText = "SELECT * FROM test"
sqlite_datareader = sqlite_cmd.ExecuteReader()
OutputTextBox.Clear()
' The SQLiteDataReader allows us to run through each row per loop
While (sqlite_datareader.Read()) ' Read() returns true if there is still a result line to read
Dim ip1, ip2, ip3, ip4 As Object
Dim textReader As String
ip1 = sqlite_datareader.GetValue(0)
ip2 = sqlite_datareader.GetValue(1)
ip3 = sqlite_datareader.GetValue(2)
ip4 = sqlite_datareader.GetValue(3)
textReader = sqlite_datareader.GetString(4)
OutputTextBox.AppendText(ip1 & "." & ip2 & "." & ip3 & "." & ip4 & " " & textReader & vbCrLf)
End While
OutputTextBox.Enabled = True
OutputTextBox.Visible = True
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
BackgroundWorker1.RunWorkerAsync()
End Sub
Function ipToBinString(ipString)
Dim ipBin
Dim splitToOctets = Split(ipString, ".")
For Each octet In splitToOctets
Dim hexString = Hex(CInt(octet)).PadLeft(2, "0")
Dim i As Integer = Convert.ToInt32(hexString, 16)
Dim s2 As String = Convert.ToString(i, 2).PadLeft(8, "0")
ipBin = ipBin & s2
Next
Return ipBin
End Function
Function ipToInt(ipString)
Dim ipBin
Dim splitToOctets = Split(ipString, ".")
For Each octet In splitToOctets
Dim hexString = Hex(CInt(octet)).PadLeft(2, "0")
Dim i As Integer = Convert.ToInt32(hexString, 16)
Dim s2 As String = Convert.ToString(i, 2).PadLeft(8, "0")
ipBin = ipBin & s2
Next
Return ipBin
End Function
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim sqlite_cmd = sqlite_mem.CreateCommand()
Dim t As New stringFunctions
' Let the SQLiteCommand object know our SQL-Query:
For i = 0 To 1024
Dim ip1, ip2, ip3, ip4 As Integer
ip1 = Math.Round((Rnd() * 255))
ip2 = Math.Round((Rnd() * 255))
ip3 = Math.Round((Rnd() * 255))
ip4 = Math.Round((Rnd() * 255))
Dim u = t.genRndStr(24)
sqlite_cmd.CommandText = "INSERT INTO test (ip1, ip2, ip3, ip4, text) VALUES (" & ip1 & "," & ip2 & "," & ip3 & "," & ip4 & ", '" & u & "');"
sqlite_cmd.ExecuteNonQuery()
Next
MsgBox("Done")
End Sub
'dump the database in memory to disk
Dim sqlite_disk
Dim memContents
Sub dumpMemToDisk()
'get all the rows from the memory database
Dim sqlite_cmd2 = sqlite_mem.CreateCommand()
sqlite_cmd2.CommandText = "SELECT * FROM test;"
memContents = sqlite_cmd2.ExecuteReader()
writeToDiskBGW.RunWorkerAsync() ' do the write to disk from memContents in a BGW thread
End Sub
'do the actual writing as a backgroundworker
Private Sub writeToDiskBGW_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles writeToDiskBGW.DoWork
'Create the disk database
Dim safePath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)
Dim dataSource = "Data Source=" & safePath & "\limbo.sqlite;Version=3;Cache Size=1048000;"
sqlite_disk = New SQLiteConnection(dataSource)
sqlite_disk.Open()
'drop the memory table then create
Dim sqlite_cmdx = sqlite_disk.CreateCommand()
' Let the SQLiteCommand object know our SQL-Query:
sqlite_cmdx.CommandText = "DROP TABLE IF EXISTS test;"
' Now lets execute the SQL ;-)
sqlite_cmdx.ExecuteNonQuery()
'create the table on the disk copy
Dim sqlite_cmd = sqlite_disk.CreateCommand()
sqlite_cmd.CommandText = createString
sqlite_cmd.ExecuteNonQuery()
While (memContents.Read())
Dim ip1, ip2, ip3, ip4 As Object
Dim textReader As String
ip1 = memContents.GetValue(0)
ip2 = memContents.GetValue(1)
ip3 = memContents.GetValue(2)
ip4 = memContents.GetValue(3)
textReader = memContents.GetString(4)
Dim sqlite_disk_write = sqlite_disk.CreateCommand()
sqlite_disk_write.CommandText = "INSERT INTO test (ip1, ip2, ip3, ip4, text) VALUES (" & ip1 & "," & ip2 & "," & ip3 & "," & ip4 & ",'" & textReader & "');"
sqlite_disk_write.ExecuteNonQuery()
End While
memContents.close()
sqlite_disk.Close()
System.Data.SQLite.SQLiteConnection.ClearAllPools()
GC.Collect()
End Sub
'dump the database on disk to memory
Sub dumpDiskToMem()
memDBDisconnect() 'shut mem db if already open
memDBConnect() 'recreates the mem db to receive disk version
'Create the disk database
Dim safePath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)
Dim dataSource = "Data Source=" & safePath & "\limbo.sqlite;Version=3;Cache Size=1048000;"
sqlite_disk = New SQLiteConnection(dataSource)
sqlite_disk.Open()
'create table
Dim sqlite_cmd = sqlite_mem.CreateCommand()
sqlite_cmd.CommandText = createString
sqlite_cmd.ExecuteNonQuery()
'get all the rows from the disk database
Dim sqlite_cmd2 = sqlite_disk.CreateCommand()
sqlite_cmd2.CommandText = "SELECT * FROM test;"
diskContents = sqlite_cmd2.ExecuteReader()
'drop the memory table then create
Dim sqlite_cmdx = sqlite_mem.CreateCommand()
' Let the SQLiteCommand object know our SQL-Query:
sqlite_cmdx.CommandText = "DROP TABLE IF EXISTS test;"
' Now lets execute the SQL ;-)
sqlite_cmd.ExecuteNonQuery()
'create table again
Dim sqlite_cmdy = sqlite_mem.CreateCommand()
' Let the SQLiteCommand object know our SQL-Query:
sqlite_cmdy.CommandText = createString
' Now lets execute the SQL ;-)
sqlite_cmd.ExecuteNonQuery()
While (diskContents.Read())
Dim ip1, ip2, ip3, ip4 As Object
Dim textReader As String
ip1 = diskContents.GetValue(0)
ip2 = diskContents.GetValue(1)
ip3 = diskContents.GetValue(2)
ip4 = diskContents.GetValue(3)
textReader = diskContents.GetString(4)
Dim sqlite_mem_write = sqlite_mem.CreateCommand()
sqlite_mem_write.CommandText = "INSERT INTO test (ip1, ip2, ip3, ip4, text) VALUES (" & ip1 & "," & ip2 & "," & ip3 & "," & ip4 & ",'" & textReader & "');"
sqlite_mem_write.ExecuteNonQuery()
End While
sqlite_disk.Close()
System.Data.SQLite.SQLiteConnection.ClearAllPools()
GC.Collect()
GC.WaitForPendingFinalizers()
End Sub
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
dumpMemToDisk()
End Sub
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
dumpDiskToMem()
End Sub
End Class
Class stringFunctions
Dim legalCharacters As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
Dim random As New Random()
Function genRndStr(size As Integer)
Dim builder As New StringBuilder()
Dim ch As Char
For i = 0 To size - 1
ch = legalCharacters(random.Next(0, legalCharacters.Length))
builder.Append(ch)
Next
Return builder.ToString()
End Function
End Class
ReferencesEdit
- ↑ https://stackoverflow.com/questions/18074925/vb-net-how-to-declare-new-empty-array-of-known-length
- ↑ https://stackoverflow.com/questions/32479842/comparison-of-dictionary-collections-and-arrays
- ↑ https://stackoverflow.com/questions/66823282/vb-net-find-words-in-pdf-using-regular-expressions
- ↑ https://learn.microsoft.com/en-us/microsoft-edge/webview2/get-started/winforms
- ↑ https://stackoverflow.com/questions/13420810/event-for-end-edit-in-a-text-box
- ↑ https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/directives/region-directive
- ↑ https://stackoverflow.com/questions/6580044/how-to-check-if-an-object-is-a-certain-type
- ↑ https://stackoverflow.com/questions/4276069/how-to-exit-an-application-properly
- ↑ https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getfullpath?view=net-7.0#system-io-path-getfullpath(system-string-system-string)
- ↑ https://learn.microsoft.com/en-us/troubleshoot/developer/dotnet/framework/general/open-database-by-sql-server-dotnet-data-provider