Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ' Download at http://brandanlasley.com/twitbot
- Imports TwitterVB2
- Imports Meebey.SmartIrc4net
- Public Class TwitBot
- Dim useINI = 1
- ' TwitBot.ini
- ' [Twitter]
- Dim Twitter_consumerkey = ""
- Dim Twitter_consumersecretkey = ""
- Dim Twitter_User_Token = ""
- Dim Twitter_User_SecretToken = ""
- Dim Twitter_Update_Rate = "11"
- Dim Twitter_Keywords = "opdx,occupy,n17,protest,wallst,wall street,riot,portlandpolice"
- Dim Twitter_Tweets_Get = "HomeTimeLine"
- Dim Twitter_TweetColor = ""
- Dim Twitter_Highlight_Keywords = ""
- Dim twitter_highlight_color = ""
- Dim Twitter_hourly_limit = "500"
- ' EOF Twitter
- ' [IRC]
- Shared irc As New IrcClient()
- Dim IRC_NETWORK = "irc.freenode.net"
- Dim IRC_PORT = "6667"
- Dim IRC_CHANNEL = "#occupyportland"
- Dim IRC_CHANNEL_PASSWORD = ""
- Dim IRC_NICKNAME = "NewsBot"
- Dim IRC_DISCRIP = "NopWorks Productions NewsBot"
- ' Login Information (Oper)
- Dim IRC_Oper_Username = ""
- Dim IRC_Oper_Password = ""
- ' Login Information (Standard User)
- Dim IRC_Nickserv_Password = ""
- ' MISC
- Dim IRC_Restart_On_Error = ""
- Dim IRC_Restart_On_Disconnection = ""
- Dim IRC_Rejoin_On_Kick = ""
- ' EOF MISC
- ' EOF IRC
- ' EOF Settings
- ' MISC
- Dim Twitter As New TwitterAPI
- Dim firsttime = 1
- Dim spam_prevention = Nothing
- Public Send_Tweet_over_irc = False
- Dim hourly_limitz = 0
- Dim first_run = 1
- ' EOF MISC
- Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
- ' Load Settings
- If useINI = 1 Then
- Dim fname = "TwitBot.Config"
- Try
- Dim fDIR As String
- Dim p As New IniFile()
- fDIR = Application.StartupPath & "\"
- If fDIR <> "" Then
- p.FileName = fDIR & "TwitBot.ini"
- fDIR = Dir(Application.StartupPath & "\" & "data\*.ini")
- ' Twitter Login Oauth
- Twitter_consumerkey = InIFilter(p.ReadString("Twitter", "Twitter_consumerkey", ""))
- Twitter_consumersecretkey = InIFilter(p.ReadString("Twitter", "Twitter_consumersecretkey", ""))
- Twitter_User_Token = InIFilter(p.ReadString("Twitter", "Twitter_User_Token", ""))
- Twitter_User_SecretToken = InIFilter(p.ReadString("Twitter", "Twitter_User_SecretToken", ""))
- ' Twitter Settings
- Twitter_Update_Rate = InIFilter(p.ReadString("Twitter", "Twitter_Update_rate", "").Replace(" ", Nothing))
- Twitter_Update_Rate = Twitter_Update_Rate & "000"
- Twitter_Keywords = InIFilter(p.ReadString("Twitter", "Twitter_Keywords", "").Replace(" ", Nothing).ToLower)
- Twitter_Tweets_Get = InIFilter(p.ReadString("Twitter", "Twitter_Tweets_Get", "").Replace(" ", Nothing))
- Twitter_TweetColor = InIFilter(p.ReadString("Twitter", "Twitter_TweetColor", "").Replace(" ", Nothing))
- Twitter_Highlight_Keywords = InIFilter(p.ReadString("Twitter", "Twitter_Highlight_keywords", "").Replace(" ", Nothing).ToLower)
- twitter_highlight_color = InIFilter(p.ReadString("Twitter", "Twitter_Highlight_color", "").Replace(" ", Nothing))
- Twitter_hourly_limit = InIFilter(p.ReadString("Twitter", "Twitter_Hourly_Limit", "").Replace(" ", Nothing))
- ' EOF Twitter
- ' IRC Network Settings
- IRC_NETWORK = InIFilter(p.ReadString("IRC", "IRC_NETWORK", "").Replace(" ", Nothing))
- IRC_PORT = InIFilter(p.ReadString("IRC", "IRC_PORT", "").Replace(" ", Nothing))
- IRC_CHANNEL = InIFilter(p.ReadString("IRC", "IRC_CHANNEL", "").Replace(" ", Nothing))
- IRC_CHANNEL_PASSWORD = InIFilter(p.ReadString("IRC", "IRC_CHANNEL_PASSWORD", ""))
- IRC_NICKNAME = InIFilter(p.ReadString("IRC", "IRC_NICKNAME", "").Replace(" ", Nothing))
- IRC_Oper_Username = InIFilter(p.ReadString("IRC", "IRC_Oper_Username", "").Replace(" ", Nothing))
- IRC_Oper_Password = InIFilter(p.ReadString("IRC", "IRC_Oper_Password", ""))
- IRC_Nickserv_Password = InIFilter(p.ReadString("IRC", "IRC_NickServ_Password", ""))
- IRC_Restart_On_Error = InIFilter(p.ReadString("IRC", "IRC_Restart_On_Error", "").Replace(" ", Nothing))
- IRC_Restart_On_Disconnection = InIFilter(p.ReadString("IRC", "IRC_Restart_On_Disconnection", "").Replace(" ", Nothing))
- IRC_Rejoin_On_Kick = InIFilter(p.ReadString("IRC", "IRC_Reloin_On_kick", "").Replace(" ", Nothing))
- ' EOF IRC Network Settings
- ' EOF
- End If
- Catch ex As Exception
- MsgBox(ex.Message.ToString)
- End Try
- If Twitter_consumerkey = Nothing Then
- MsgBox("Error: Twitter Consumer Key Missing", MsgBoxStyle.Critical)
- End
- ElseIf Twitter_consumersecretkey = Nothing Then
- MsgBox("Error: Twitter Secret Consumer Key Missing", MsgBoxStyle.Critical)
- End
- ElseIf Twitter_User_Token = Nothing Then
- MsgBox("Error: Twitter User Token Missing", MsgBoxStyle.Critical)
- End
- ElseIf Twitter_User_SecretToken = Nothing Then
- MsgBox("Error: Twitter Secret Token Missing", MsgBoxStyle.Critical)
- End
- ElseIf IRC_NETWORK = Nothing Then
- MsgBox("Error: IRC Network Missing", MsgBoxStyle.Critical)
- End
- ElseIf IRC_PORT = Nothing Then
- MsgBox("Error: IRC PORT Missing", MsgBoxStyle.Critical)
- End
- ElseIf IRC_CHANNEL = Nothing Then
- MsgBox("Error: IRC CHANNEL Missing", MsgBoxStyle.Critical)
- End
- ElseIf IRC_NICKNAME = Nothing Then
- MsgBox("Error: IRC NICKNAME Missing", MsgBoxStyle.Critical)
- End
- ElseIf Twitter_Update_Rate = Nothing Then
- MsgBox("Error: Twitter Update Rate Missing", MsgBoxStyle.Critical)
- End
- End If
- End If
- Update.Interval = Twitter_Update_Rate
- ' MsgBox(Twitter_consumerkey & vbNewLine & _
- 'Twitter_consumersecretkey & vbNewLine & _
- 'Twitter_User_Token & vbNewLine & _
- 'Twitter_User_SecretToken & vbNewLine & _
- 'Twitter_Update_Rate & vbNewLine & _
- 'Twitter_Keywords & vbNewLine & _
- 'Twitter_Tweets_Get & vbNewLine & _
- 'Twitter_TweetColor & vbNewLine & _
- 'Twitter_Highlight_Keywords & vbNewLine & _
- 'twitter_highlight_color & vbNewLine & _
- 'Twitter_hourly_limit & vbNewLine & _
- 'IRC_NETWORK & vbNewLine & _
- 'IRC_PORT & vbNewLine & _
- 'IRC_CHANNEL & vbNewLine & _
- 'IRC_CHANNEL_PASSWORD & vbNewLine & _
- 'IRC_NICKNAME & vbNewLine & _
- 'IRC_DISCRIP & vbNewLine & _
- 'IRC_Oper_Username & vbNewLine & _
- 'IRC_Oper_Password & vbNewLine & _
- 'IRC_Nickserv_Password & vbNewLine & _
- 'IRC_Restart_On_Error & vbNewLine & _
- 'IRC_Restart_On_Disconnection & vbNewLine & _
- 'IRC_Rejoin_On_Kick)
- Try
- Twitter.AuthenticateWith(Twitter_consumerkey, Twitter_consumersecretkey, Twitter_User_Token, Twitter_User_SecretToken)
- For Each tweet As TwitterStatus In Twitter.HomeTimeline
- TwitterFeed.AppendText(tweet.User.ScreenName + ": " + tweet.Text & vbNewLine & vbNewLine)
- Next
- Catch ex As Exception
- MsgBox(ex.Message)
- End Try
- ' IRC CONNECTION
- AddHandler irc.OnConnected, AddressOf irc_OnConnected
- irc.Connect(IRC_NETWORK, IRC_PORT)
- End Sub
- Public Function InIFilter(ByVal text As String)
- Dim y = text
- If text.Contains(";"c) Then
- y = text.Substring(0, text.IndexOf(";"c))
- End If
- If y = Nothing Then
- Return Nothing
- End If
- y = y.Replace("""", Nothing)
- Return y
- End Function
- Private Sub Hour_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Hour.Tick
- hourly_limitz = 0
- End Sub
- Private Sub Update_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Update.Tick
- TwitterFeed.Clear()
- If (Twitter_Tweets_Get).ToLower = "hometimeline" Then
- Try
- Twitter.AuthenticateWith(Twitter_consumerkey, Twitter_consumersecretkey, Twitter_User_Token, Twitter_User_SecretToken)
- For Each tweet As TwitterStatus In Twitter.HomeTimeline
- If Twitter_Keywords = Nothing = False Then
- Dim words As String() = Twitter_Keywords.Split(New Char() {","c})
- Dim word As String
- For Each word In words
- If tweet.Text.ToLower.Replace(" ", Nothing).Contains(word) Then
- TwitterFeed.AppendText(tweet.User.ScreenName + ": " + tweet.Text & vbNewLine & vbNewLine)
- GoTo skip
- End If
- Next
- End If
- Next
- Catch ex As Exception
- MsgBox(ex.Message)
- Return
- End Try
- ElseIf (Twitter_Tweets_Get).ToLower = "friendstimeline" Then
- Try
- Twitter.AuthenticateWith(Twitter_consumerkey, Twitter_consumersecretkey, Twitter_User_Token, Twitter_User_SecretToken)
- For Each tweet As TwitterStatus In Twitter.FriendsTimeline
- If Twitter_Keywords = Nothing = False Then
- Dim words As String() = Twitter_Keywords.Split(New Char() {","c})
- Dim word As String
- For Each word In words
- If tweet.Text.ToLower.Replace(" ", Nothing).Contains(word) Then
- TwitterFeed.AppendText(tweet.User.ScreenName + ": " + tweet.Text & vbNewLine & vbNewLine)
- GoTo skip
- End If
- Next
- End If
- Next
- Catch ex As Exception
- MsgBox(ex.Message)
- Return
- End Try
- ElseIf (Twitter_Tweets_Get).ToLower = "publictimeline" Then
- Try
- Twitter.AuthenticateWith(Twitter_consumerkey, Twitter_consumersecretkey, Twitter_User_Token, Twitter_User_SecretToken)
- For Each tweet As TwitterStatus In Twitter.PublicTimeline
- If Twitter_Keywords = Nothing = False Then
- Dim words As String() = (Twitter_Keywords).ToString.ToLower.Split(New Char() {","c})
- Dim word As String
- For Each word In words
- If tweet.Text.ToLower.Replace(" ", Nothing).Contains(word) Then
- TwitterFeed.AppendText(tweet.User.ScreenName + ": " + tweet.Text & vbNewLine & vbNewLine)
- GoTo skip
- End If
- Next
- End If
- Next
- Catch ex As Exception
- MsgBox(ex.Message)
- Return
- End Try
- ElseIf (Twitter_Tweets_Get).ToLower = "usertimeline" Then
- Try
- Twitter.AuthenticateWith(Twitter_consumerkey, Twitter_consumersecretkey, Twitter_User_Token, Twitter_User_SecretToken)
- For Each tweet As TwitterStatus In Twitter.UserTimeline
- If Twitter_Keywords = Nothing = False Then
- Dim words As String() = (Twitter_Keywords).ToString.ToLower.Split(New Char() {","c})
- Dim word As String
- For Each word In words
- If tweet.Text.ToLower.Replace(" ", Nothing).Contains(word.ToLower) Then
- TwitterFeed.AppendText(tweet.User.ScreenName + ": " + tweet.Text & vbNewLine & vbNewLine)
- GoTo skip
- End If
- Next
- End If
- Next
- Catch ex As Exception
- MsgBox(ex.Message)
- Return
- End Try
- End If
- Skip:
- Try
- Dim lines As String() = Old_Twitter_feed.Lines '<- array create here.
- For i As Integer = 0 To lines.GetUpperBound(0)
- TwitterFeed.Text = TwitterFeed.Lines(i).Replace(Old_Twitter_feed.Lines(i), Nothing)
- Next i
- Catch ex As Exception
- End Try
- If TwitterFeed.Text = Nothing = False Then
- If firsttime = 0 Then
- Old_Twitter_feed.Text = TwitterFeed.Text + Old_Twitter_feed.Text
- End If
- End If
- If firsttime = 1 Then
- firsttime = 0
- Old_Twitter_feed.Text = TwitterFeed.Text
- End If
- ' IRC SENDING PART
- If Send_Tweet_over_irc = True Then
- Dim lines As String() = TwitterFeed.Lines '<- array create here.
- For i As Integer = 0 To lines.GetUpperBound(0)
- If spam_prevention = TwitterFeed.Lines(i) Then
- Return
- End If
- If hourly_limitz < Twitter_hourly_limit Then
- If Twitter_Highlight_Keywords = Nothing = False Then
- Dim words As String() = (Twitter_Highlight_Keywords).ToString.ToLower.Replace(" ", Nothing).Split(New Char() {","c})
- Dim word As String
- For Each word In words
- If TwitterFeed.Lines(i).ToLower.Contains(word) Then
- irc.SendMessage(SendType.Message, IRC_CHANNEL, "" & twitter_highlight_color & TwitterFeed.Lines(i))
- GoTo skip2
- End If
- Next
- End If
- If Twitter_TweetColor = Nothing Then
- irc.SendMessage(SendType.Message, IRC_CHANNEL, TwitterFeed.Lines(i))
- Else
- irc.SendMessage(SendType.Message, IRC_CHANNEL, "" & Twitter_TweetColor & TwitterFeed.Lines(i))
- End If
- skip2:
- spam_prevention = TwitterFeed.Lines(i)
- hourly_limitz = hourly_limitz + 1
- End If
- Next i
- End If
- If first_run = 1 Then
- first_run = 0
- Send_Tweet_over_irc = True
- End If
- End Sub
- Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
- Update.Stop()
- End Sub
- Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
- Update.Start()
- End Sub
- '''' IRC CLIENT
- Private Sub irc_OnConnected(ByVal sender As Object, ByVal e As System.EventArgs)
- irc.Login(IRC_NICKNAME, IRC_DISCRIP)
- irc.Listen(False)
- AddHandler irc.OnChannelMessage, AddressOf irc_OnChannelMessage
- AddHandler irc.OnDisconnected, AddressOf irc_disconnect
- AddHandler irc.OnDisconnecting, AddressOf irc_disconnect
- AddHandler irc.OnConnectionError, AddressOf irc_disconnect
- AddHandler irc.OnJoin, AddressOf irc_OnJoin
- AddHandler irc.OnPart, AddressOf irc_Onpart
- IRC_CONNECTION.RunWorkerAsync()
- irc.RfcJoin(IRC_CHANNEL, IRC_CHANNEL_PASSWORD)
- If IRC_CHANNEL_PASSWORD = Nothing = False Then
- irc.SendMessage(SendType.Message, "nickserv", "idenify " & IRC_Nickserv_Password)
- End If
- If IRC_Oper_Username = Nothing = False Then
- If IRC_Oper_Password = Nothing = False Then
- irc.RfcOper(IRC_Oper_Username, IRC_Oper_Password)
- End If
- End If
- If IRC_Rejoin_On_Kick = "1" Then
- irc.AutoRejoinOnKick = True
- End If
- Exit Sub
- pp:
- Application.Restart()
- End Sub
- Private Sub irc_Onpart(ByVal sender As Object, ByVal e As PartEventArgs)
- End Sub
- Private Sub irc_OnJoin(ByVal sender As Object, ByVal e As JoinEventArgs)
- End Sub
- Private Sub irc_disconnect(ByVal sender As Object, ByVal e As Meebey.SmartIrc4net.IrcEventArgs)
- If IRC_Restart_On_Disconnection = "1" Then
- Application.Restart()
- End If
- End Sub
- Private Sub irc_OnChannelMessage(ByVal sender As Object, ByVal e As Meebey.SmartIrc4net.IrcEventArgs)
- Dim msg As String = e.Data.Message.ToLower
- If msg = "!stop" Then
- Send_Tweet_over_irc = False
- irc.SendMessage(SendType.Message, IRC_CHANNEL, "Live Twitter Feed Stopped")
- ElseIf msg = "!start" Then
- Send_Tweet_over_irc = True
- irc.SendMessage(SendType.Message, IRC_CHANNEL, "Live Twitter Feed Started")
- End If
- If IRC_CONNECTION.IsBusy = False Then
- IRC_CONNECTION.RunWorkerAsync()
- End If
- If msg = "!about" Then
- irc.SendMessage(SendType.Message, IRC_CHANNEL, "Programmed By: Brandan Tyler Lasley Using TwitterVB2 dll")
- End If
- Exit Sub
- PP:
- Application.Restart()
- End Sub
- Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
- Send_Tweet_over_irc = True
- End Sub
- Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
- Send_Tweet_over_irc = False
- End Sub
- Private Sub IRC_CONNECTION_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles IRC_CONNECTION.DoWork
- On Error GoTo pp
- While True
- irc.ReadLine(False)
- Threading.Thread.Sleep(100)
- End While
- Exit Sub
- pp:
- Application.Restart()
- End Sub
- End Class
- Public Class IniFile
- ' Managed IniFile Class
- #Region "Private variables"
- ' =======================================================================
- ' Private variables used in the class
- Private mFileName As String = ""
- Private mDs As Data.DataSet
- #End Region
- #Region "Contructors"
- ' =======================================================================
- ' Constructors
- Public Sub New()
- 'Nothing here
- End Sub
- Public Sub New(ByVal iniFileName As String)
- ' Open the IniFile
- FileName = iniFileName
- End Sub
- #End Region
- #Region "Methodes"
- ' =======================================================================
- ' Methodes
- Public Overloads Function ReadString(ByVal section As String, ByVal key As String) As String
- ' Function ReadString Number 1
- ' Read string from INI Dataset
- ' Use function number 2
- ' Use an empty string as defaultvalue
- Return Me.ReadString(section, key, "")
- End Function
- Public Overloads Function ReadString(ByVal section As String, ByVal key As String, ByVal defaultValue As String) As String
- ' Function ReadString Number 2
- ' Read string from INI Dataset
- Return Read(section, key, defaultValue)
- End Function
- Public Overloads Function ReadString(ByVal section As String, ByVal key As String, ByVal defaultValue As String, ByVal iniFileName As String) As String
- ' Function ReadString Number 3
- ' Open the IniFile
- FileName = iniFileName
- ' Read string from INI Dataset
- ' Use function number 2
- Return Me.ReadString(section, key, defaultValue)
- End Function
- Public Overloads Function ReadInteger(ByVal section As String, ByVal key As String) As Integer
- ' Function ReadInteger Number 1
- ' Store return value
- ' Use function number 2
- ' Use 0 as defaultvalue
- Return Me.ReadInteger(section, key, 0)
- End Function
- Public Overloads Function ReadInteger(ByVal section As String, ByVal key As String, ByVal defaultValue As Integer) As Integer
- ' Function ReadInteger Number 2
- ' Store return value
- Dim ret As Integer
- Dim tmpRet As String
- ' Read string from INI Dataset
- ' First convert DefaultValue to a string to use the Common Read function
- tmpRet = Read(section, key, CType(defaultValue, String))
- Try
- ' Convert the Value to an Integer
- ret = CType(tmpRet, Integer)
- Catch
- ' When the value couldn't convert to a integer, return zero
- ret = 0
- End Try
- Return ret
- End Function
- Public Overloads Function ReadInteger(ByVal section As String, ByVal key As String, ByVal defaultValue As Integer, ByVal iniFileName As String) As Integer
- ' Function ReadInteger Number 3
- ' Open the IniFile
- FileName = iniFileName
- ' Use ReadInteger function number 2
- Return Me.ReadInteger(section, key, defaultValue)
- End Function
- Public Function SectionNames() As Collections.ArrayList
- ' Store return value in an arraylist
- Dim ret As New Collections.ArrayList()
- Dim table As Data.DataTable
- ' Loop through all the Tables
- For Each table In mDs.Tables
- ' Add tablename to the ArrayList
- ret.Add(table.TableName)
- Next
- Return ret
- End Function
- Public Overloads Sub WriteString(ByVal section As String, ByVal key As String, ByVal value As String)
- ' Function WriteString Number 1
- ' Store data in dataset
- Write(section, key, value)
- ' Write dataset back to disk
- DumpDatasetToIni()
- End Sub
- Public Overloads Sub WriteString(ByVal section As String, ByVal key As String, ByVal value As String, ByVal iniFileName As String)
- ' Function WriteString Number 2
- ' Open the IniFile
- FileName = iniFileName
- ' Use WriteString function number 1
- Me.WriteString(section, key, value)
- End Sub
- Public Overloads Sub WriteInteger(ByVal section As String, ByVal key As String, ByVal value As Integer)
- ' Function WriteInteger Number 1
- ' First convert Value to a string to use the WriteString function number 1
- Me.WriteString(section, key, value.ToString)
- End Sub
- Public Overloads Sub WriteInteger(ByVal section As String, ByVal key As String, ByVal value As Integer, ByVal iniFileName As String)
- ' Function WriteInteger Number 2
- ' First convert Value to a string to use the WriteString function number 2
- Me.WriteString(section, key, value.ToString, iniFileName)
- End Sub
- Public Overloads Sub DeleteSection(ByVal section As String)
- ' Function DeleteSection Number 1
- ' Delete 'Section' Table from Dataset
- ' First check if section exists
- If Not (mDs.Tables(section) Is Nothing) Then
- ' Section is found, so kill it
- mDs.Tables.Remove(section)
- ' Write dataset back to disk
- DumpDatasetToIni()
- End If
- End Sub
- Public Overloads Sub DeleteSection(ByVal section As String, ByVal iniFileName As String)
- ' Function DeleteSection Number 2
- ' Open the IniFile
- FileName = iniFileName
- ' Use DeleteSection function number 1
- Me.DeleteSection(section)
- End Sub
- #End Region
- #Region "Properties"
- ' =======================================================================
- ' Properties
- Public Property FileName() As String
- Get
- ' Return Filename
- Return mFileName
- End Get
- Set(ByVal Value As String)
- ' Check if File is allready open
- If Value.Trim <> mFileName Then
- ' If not, open it
- mFileName = Value
- LoadIniToDataSet()
- End If
- End Set
- End Property
- Public ReadOnly Property DataSet() As Data.DataSet
- Get
- ' Return Dataset
- Return mDs
- End Get
- End Property
- #End Region
- #Region "Private Section"
- ' =======================================================================
- ' Private Section
- Private Function Read(ByVal section As String, ByVal key As String, ByVal defaultValue As String) As String
- ' Store return value
- Dim ret As String
- Try
- ' Section = TableName
- ' Key = ColumnName
- ' Row = 0, because there is only one row for each table
- ' Get the value from the dataset
- ret = mDs.Tables(section).Rows(0).Item(key).ToString
- Catch
- ' If the Section or Key isn't found return the DefaultValue
- ret = defaultValue
- End Try
- Return ret
- End Function
- Private Sub Write(ByVal section As String, ByVal key As String, ByVal value As String)
- ' Section = Table
- ' Key = Column
- ' Row = 0, because there is only one row for each table
- ' Look for section in Dataset
- If (mDs.Tables(section) Is Nothing) Then
- ' Section is not found
- ' Add section to the dataset
- mDs.Tables.Add(section)
- ' Add Key to Section
- mDs.Tables(section).Columns.Add(key)
- ' We must add a new row to the dataset
- Dim row As Data.DataRow
- row = mDs.Tables(section).NewRow
- ' Add Value to Key
- row.Item(key) = value
- mDs.Tables(section).Rows.Add(row)
- Else
- ' Section was found, now look for key in section
- If (mDs.Tables(section).Columns(key) Is Nothing) Then
- ' Key is not found
- ' Add key to the section
- mDs.Tables(section).Columns.Add(key)
- End If
- ' Update Value for key
- mDs.Tables(section).Rows(0).Item(key) = value
- End If
- End Sub
- Private Overloads Sub LoadIniToDataSet()
- ' Initialise Dataset
- mDs = New Data.DataSet()
- ' Open the File
- Dim file As New IO.FileInfo(mFileName)
- ' Create DatasetName from IniFileName by removing the file extention
- mDs.DataSetName = file.Name.Remove(file.Name.IndexOf(file.Extension), file.Extension.Length)
- ' Check if inifile exists on specified path
- If file.Exists() Then
- ' Store each Section as a Table in the Dataset
- Dim table As Data.DataTable
- ' Define row to fill with KeyValue
- Dim row As Data.DataRow
- ' A switch to keep track when we have add the row to the table
- Dim addRow As Boolean = False
- ' A switch to keep track when we have add the row to the table
- Dim skipSection As Boolean = False
- ' Use a filestream to read the IniFile
- Dim fileStream As New IO.StreamReader(mFileName)
- Dim readLine As String
- ' Read the first line
- readLine = fileStream.ReadLine
- ' Loop to the end of the File
- Do While Not (readLine Is Nothing)
- ' Trim all leading en ending spaces
- readLine = readLine.Trim()
- ' Skip empty lines and commented lines
- If readLine <> "" And Not readLine.StartsWith(";") Then
- ' Check if the line is a Section Header
- If readLine.StartsWith("[") AndAlso readLine.EndsWith("]") Then
- ' A new Section means a new Table
- ' Before we create a new table
- ' add all the values to the previous created table
- If addRow Then
- table.Rows.Add(row)
- End If
- ' remove brackets from readline
- readLine = readLine.TrimStart("["c)
- readLine = readLine.TrimEnd("]"c)
- ' Tablename is SectionName
- ' Check if table allready exists
- ' If so, skip the rest of the section
- ' An iniFile can't have double sections
- ' First set it to True, will be corrected a few lines below
- skipSection = True
- table = mDs.Tables(readLine)
- If (table Is Nothing) Then
- ' If not, Create new table
- table = New Data.DataTable(readLine)
- ' Add Table to Dataset
- mDs.Tables.Add(table)
- ' Adds a new row to the table
- row = table.NewRow
- skipSection = False
- End If
- ' Clear switch
- addRow = False
- Else
- If Not skipSection Then
- ' Use a string array to store data
- Dim splitLine() As String
- ' Split the line by a =
- ' SplitDate(0) holds the Key
- ' SplitDate(1) holds the KeyValue
- splitLine = readLine.Split("="c)
- ' Columnname is Key
- ' Check if Key allready exists
- ' if so Skip it, a section can't have double keys
- If (table.Columns(splitLine(0)) Is Nothing) Then
- ' Add Key as a new column to the table
- table.Columns.Add(Trim(splitLine(0)))
- ' Check if line is splitted ok
- If splitLine.Length = 2 Then
- ' Fill Key-column with KeyValue
- row.Item(Trim(splitLine(0))) = Trim(splitLine(1))
- Else
- ' Fill Key-column with empty string
- row.Item(splitLine(0)) = ""
- End If
- ' Set switch for adding row
- addRow = True
- End If
- End If
- End If
- End If
- ' Read next Line
- readLine = fileStream.ReadLine
- Loop
- ' Don't forget the last entries
- If addRow Then
- table.Rows.Add(row)
- End If
- ' Close file
- fileStream.Close()
- End If
- End Sub
- Private Sub DumpDatasetToIni()
- ' Check if inifile exists on specified path
- If IO.File.Exists(mFileName) Then
- ' if, so....delete it
- IO.File.Delete(mFileName)
- End If
- ' Use a StreamWriter to make a new inifile
- Dim file As IO.StreamWriter = IO.File.CreateText(mFileName)
- ' Section = TableName
- ' Key = ColumnName
- ' Row = 0, because there is only one row for each table
- Dim table As Data.DataTable
- Dim col As Data.DataColumn
- Dim value As String
- ' Loop through all sections
- For Each table In mDs.Tables
- ' Write section name
- file.WriteLine("[" & table.TableName & "]")
- ' Loop through all key's in section
- For Each col In table.Columns
- ' Find value for key
- value = table.Rows(0).Item(col).ToString
- ' Write Key and Value
- file.WriteLine(col.ColumnName & "=" & value)
- Next
- ' Make an empty line between the sections
- file.WriteLine("")
- Next
- ' Close IniFile
- file.Close()
- End Sub
- #End Region
- End Class
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement