Advertisement
Brandan

#OccupyPortland TwitBot SRC (MAIN 1 FORM)

Nov 19th, 2011
298
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VB.NET 32.55 KB | None | 0 0
  1. ' Download at http://brandanlasley.com/twitbot
  2.  
  3.  
  4. Imports TwitterVB2
  5. Imports Meebey.SmartIrc4net
  6.  
  7. Public Class TwitBot
  8.     Dim useINI = 1
  9.     ' TwitBot.ini
  10.  
  11.     ' [Twitter]
  12.     Dim Twitter_consumerkey = ""
  13.     Dim Twitter_consumersecretkey = ""
  14.     Dim Twitter_User_Token = ""
  15.     Dim Twitter_User_SecretToken = ""
  16.     Dim Twitter_Update_Rate = "11"
  17.     Dim Twitter_Keywords = "opdx,occupy,n17,protest,wallst,wall street,riot,portlandpolice"
  18.     Dim Twitter_Tweets_Get = "HomeTimeLine"
  19.     Dim Twitter_TweetColor = ""
  20.     Dim Twitter_Highlight_Keywords = ""
  21.     Dim twitter_highlight_color = ""
  22.     Dim Twitter_hourly_limit = "500"
  23.  
  24.     ' EOF Twitter
  25.  
  26.     ' [IRC]
  27.     Shared irc As New IrcClient()
  28.     Dim IRC_NETWORK = "irc.freenode.net"
  29.     Dim IRC_PORT = "6667"
  30.     Dim IRC_CHANNEL = "#occupyportland"
  31.     Dim IRC_CHANNEL_PASSWORD = ""
  32.     Dim IRC_NICKNAME = "NewsBot"
  33.     Dim IRC_DISCRIP = "NopWorks Productions NewsBot"
  34.  
  35.     ' Login Information (Oper)
  36.  
  37.     Dim IRC_Oper_Username = ""
  38.     Dim IRC_Oper_Password = ""
  39.  
  40.     ' Login Information (Standard User)
  41.  
  42.     Dim IRC_Nickserv_Password = ""
  43.  
  44.     ' MISC
  45.  
  46.     Dim IRC_Restart_On_Error = ""
  47.     Dim IRC_Restart_On_Disconnection = ""
  48.     Dim IRC_Rejoin_On_Kick = ""
  49.  
  50.     ' EOF MISC
  51.  
  52.     ' EOF IRC
  53.  
  54.     ' EOF Settings
  55.  
  56.     ' MISC
  57.     Dim Twitter As New TwitterAPI
  58.     Dim firsttime = 1
  59.     Dim spam_prevention = Nothing
  60.     Public Send_Tweet_over_irc = False
  61.     Dim hourly_limitz = 0
  62.     Dim first_run = 1
  63.  
  64.     ' EOF MISC
  65.  
  66.     Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  67.         ' Load Settings
  68.         If useINI = 1 Then
  69.             Dim fname = "TwitBot.Config"
  70.             Try
  71.                 Dim fDIR As String
  72.                 Dim p As New IniFile()
  73.                 fDIR = Application.StartupPath & "\"
  74.                 If fDIR <> "" Then
  75.                     p.FileName = fDIR & "TwitBot.ini"
  76.                     fDIR = Dir(Application.StartupPath & "\" & "data\*.ini")
  77.  
  78.                     ' Twitter Login Oauth
  79.                     Twitter_consumerkey = InIFilter(p.ReadString("Twitter", "Twitter_consumerkey", ""))
  80.                     Twitter_consumersecretkey = InIFilter(p.ReadString("Twitter", "Twitter_consumersecretkey", ""))
  81.                     Twitter_User_Token = InIFilter(p.ReadString("Twitter", "Twitter_User_Token", ""))
  82.                     Twitter_User_SecretToken = InIFilter(p.ReadString("Twitter", "Twitter_User_SecretToken", ""))
  83.  
  84.                     ' Twitter Settings
  85.                     Twitter_Update_Rate = InIFilter(p.ReadString("Twitter", "Twitter_Update_rate", "").Replace(" ", Nothing))
  86.                     Twitter_Update_Rate = Twitter_Update_Rate & "000"
  87.                     Twitter_Keywords = InIFilter(p.ReadString("Twitter", "Twitter_Keywords", "").Replace(" ", Nothing).ToLower)
  88.                     Twitter_Tweets_Get = InIFilter(p.ReadString("Twitter", "Twitter_Tweets_Get", "").Replace(" ", Nothing))
  89.                     Twitter_TweetColor = InIFilter(p.ReadString("Twitter", "Twitter_TweetColor", "").Replace(" ", Nothing))
  90.                     Twitter_Highlight_Keywords = InIFilter(p.ReadString("Twitter", "Twitter_Highlight_keywords", "").Replace(" ", Nothing).ToLower)
  91.                     twitter_highlight_color = InIFilter(p.ReadString("Twitter", "Twitter_Highlight_color", "").Replace(" ", Nothing))
  92.                     Twitter_hourly_limit = InIFilter(p.ReadString("Twitter", "Twitter_Hourly_Limit", "").Replace(" ", Nothing))
  93.  
  94.                     ' EOF Twitter
  95.  
  96.                     ' IRC Network Settings
  97.  
  98.                     IRC_NETWORK = InIFilter(p.ReadString("IRC", "IRC_NETWORK", "").Replace(" ", Nothing))
  99.                     IRC_PORT = InIFilter(p.ReadString("IRC", "IRC_PORT", "").Replace(" ", Nothing))
  100.                     IRC_CHANNEL = InIFilter(p.ReadString("IRC", "IRC_CHANNEL", "").Replace(" ", Nothing))
  101.                     IRC_CHANNEL_PASSWORD = InIFilter(p.ReadString("IRC", "IRC_CHANNEL_PASSWORD", ""))
  102.                     IRC_NICKNAME = InIFilter(p.ReadString("IRC", "IRC_NICKNAME", "").Replace(" ", Nothing))
  103.                     IRC_Oper_Username = InIFilter(p.ReadString("IRC", "IRC_Oper_Username", "").Replace(" ", Nothing))
  104.                     IRC_Oper_Password = InIFilter(p.ReadString("IRC", "IRC_Oper_Password", ""))
  105.                     IRC_Nickserv_Password = InIFilter(p.ReadString("IRC", "IRC_NickServ_Password", ""))
  106.                     IRC_Restart_On_Error = InIFilter(p.ReadString("IRC", "IRC_Restart_On_Error", "").Replace(" ", Nothing))
  107.                     IRC_Restart_On_Disconnection = InIFilter(p.ReadString("IRC", "IRC_Restart_On_Disconnection", "").Replace(" ", Nothing))
  108.                     IRC_Rejoin_On_Kick = InIFilter(p.ReadString("IRC", "IRC_Reloin_On_kick", "").Replace(" ", Nothing))
  109.  
  110.                     ' EOF IRC Network Settings
  111.  
  112.                     ' EOF
  113.                 End If
  114.             Catch ex As Exception
  115.                 MsgBox(ex.Message.ToString)
  116.             End Try
  117.             If Twitter_consumerkey = Nothing Then
  118.                 MsgBox("Error: Twitter Consumer Key Missing", MsgBoxStyle.Critical)
  119.                 End
  120.             ElseIf Twitter_consumersecretkey = Nothing Then
  121.                 MsgBox("Error: Twitter Secret Consumer Key Missing", MsgBoxStyle.Critical)
  122.                 End
  123.             ElseIf Twitter_User_Token = Nothing Then
  124.                 MsgBox("Error: Twitter User Token Missing", MsgBoxStyle.Critical)
  125.                 End
  126.             ElseIf Twitter_User_SecretToken = Nothing Then
  127.                 MsgBox("Error: Twitter Secret Token Missing", MsgBoxStyle.Critical)
  128.                 End
  129.             ElseIf IRC_NETWORK = Nothing Then
  130.                 MsgBox("Error: IRC Network Missing", MsgBoxStyle.Critical)
  131.                 End
  132.             ElseIf IRC_PORT = Nothing Then
  133.                 MsgBox("Error: IRC PORT Missing", MsgBoxStyle.Critical)
  134.                 End
  135.             ElseIf IRC_CHANNEL = Nothing Then
  136.                 MsgBox("Error: IRC CHANNEL Missing", MsgBoxStyle.Critical)
  137.                 End
  138.             ElseIf IRC_NICKNAME = Nothing Then
  139.                 MsgBox("Error: IRC NICKNAME Missing", MsgBoxStyle.Critical)
  140.                 End
  141.             ElseIf Twitter_Update_Rate = Nothing Then
  142.                 MsgBox("Error: Twitter Update Rate Missing", MsgBoxStyle.Critical)
  143.                 End
  144.             End If
  145.         End If
  146.         Update.Interval = Twitter_Update_Rate
  147.  
  148.         '   MsgBox(Twitter_consumerkey & vbNewLine & _
  149.         'Twitter_consumersecretkey & vbNewLine & _
  150.         'Twitter_User_Token & vbNewLine & _
  151.         'Twitter_User_SecretToken & vbNewLine & _
  152.         'Twitter_Update_Rate & vbNewLine & _
  153.         'Twitter_Keywords & vbNewLine & _
  154.         'Twitter_Tweets_Get & vbNewLine & _
  155.         'Twitter_TweetColor & vbNewLine & _
  156.         'Twitter_Highlight_Keywords & vbNewLine & _
  157.         'twitter_highlight_color & vbNewLine & _
  158.         'Twitter_hourly_limit & vbNewLine & _
  159.         'IRC_NETWORK & vbNewLine & _
  160.         'IRC_PORT & vbNewLine & _
  161.         'IRC_CHANNEL & vbNewLine & _
  162.         'IRC_CHANNEL_PASSWORD & vbNewLine & _
  163.         'IRC_NICKNAME & vbNewLine & _
  164.         'IRC_DISCRIP & vbNewLine & _
  165.         'IRC_Oper_Username & vbNewLine & _
  166.         'IRC_Oper_Password & vbNewLine & _
  167.         'IRC_Nickserv_Password & vbNewLine & _
  168.         'IRC_Restart_On_Error & vbNewLine & _
  169.         'IRC_Restart_On_Disconnection & vbNewLine & _
  170.         'IRC_Rejoin_On_Kick)
  171.  
  172.         Try
  173.             Twitter.AuthenticateWith(Twitter_consumerkey, Twitter_consumersecretkey, Twitter_User_Token, Twitter_User_SecretToken)
  174.             For Each tweet As TwitterStatus In Twitter.HomeTimeline
  175.                 TwitterFeed.AppendText(tweet.User.ScreenName + ": " + tweet.Text & vbNewLine & vbNewLine)
  176.             Next
  177.         Catch ex As Exception
  178.             MsgBox(ex.Message)
  179.         End Try
  180.  
  181.         ' IRC CONNECTION
  182.         AddHandler irc.OnConnected, AddressOf irc_OnConnected
  183.         irc.Connect(IRC_NETWORK, IRC_PORT)
  184.     End Sub
  185.  
  186.     Public Function InIFilter(ByVal text As String)
  187.         Dim y = text
  188.         If text.Contains(";"c) Then
  189.             y = text.Substring(0, text.IndexOf(";"c))
  190.         End If
  191.         If y = Nothing Then
  192.             Return Nothing
  193.         End If
  194.         y = y.Replace("""", Nothing)
  195.         Return y
  196.     End Function
  197.  
  198.     Private Sub Hour_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Hour.Tick
  199.         hourly_limitz = 0
  200.     End Sub
  201.  
  202.     Private Sub Update_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Update.Tick
  203.         TwitterFeed.Clear()
  204.         If (Twitter_Tweets_Get).ToLower = "hometimeline" Then
  205.             Try
  206.                 Twitter.AuthenticateWith(Twitter_consumerkey, Twitter_consumersecretkey, Twitter_User_Token, Twitter_User_SecretToken)
  207.                 For Each tweet As TwitterStatus In Twitter.HomeTimeline
  208.                     If Twitter_Keywords = Nothing = False Then
  209.                         Dim words As String() = Twitter_Keywords.Split(New Char() {","c})
  210.                         Dim word As String
  211.                         For Each word In words
  212.                             If tweet.Text.ToLower.Replace(" ", Nothing).Contains(word) Then
  213.                                 TwitterFeed.AppendText(tweet.User.ScreenName + ": " + tweet.Text & vbNewLine & vbNewLine)
  214.                                 GoTo skip
  215.                             End If
  216.                         Next
  217.                     End If
  218.                 Next
  219.             Catch ex As Exception
  220.                 MsgBox(ex.Message)
  221.                 Return
  222.             End Try
  223.         ElseIf (Twitter_Tweets_Get).ToLower = "friendstimeline" Then
  224.             Try
  225.                 Twitter.AuthenticateWith(Twitter_consumerkey, Twitter_consumersecretkey, Twitter_User_Token, Twitter_User_SecretToken)
  226.                 For Each tweet As TwitterStatus In Twitter.FriendsTimeline
  227.                     If Twitter_Keywords = Nothing = False Then
  228.                         Dim words As String() = Twitter_Keywords.Split(New Char() {","c})
  229.                         Dim word As String
  230.                         For Each word In words
  231.                             If tweet.Text.ToLower.Replace(" ", Nothing).Contains(word) Then
  232.                                 TwitterFeed.AppendText(tweet.User.ScreenName + ": " + tweet.Text & vbNewLine & vbNewLine)
  233.                                 GoTo skip
  234.                             End If
  235.                         Next
  236.                     End If
  237.                 Next
  238.             Catch ex As Exception
  239.                 MsgBox(ex.Message)
  240.                 Return
  241.             End Try
  242.         ElseIf (Twitter_Tweets_Get).ToLower = "publictimeline" Then
  243.             Try
  244.                 Twitter.AuthenticateWith(Twitter_consumerkey, Twitter_consumersecretkey, Twitter_User_Token, Twitter_User_SecretToken)
  245.                 For Each tweet As TwitterStatus In Twitter.PublicTimeline
  246.                     If Twitter_Keywords = Nothing = False Then
  247.                         Dim words As String() = (Twitter_Keywords).ToString.ToLower.Split(New Char() {","c})
  248.                         Dim word As String
  249.                         For Each word In words
  250.                             If tweet.Text.ToLower.Replace(" ", Nothing).Contains(word) Then
  251.                                 TwitterFeed.AppendText(tweet.User.ScreenName + ": " + tweet.Text & vbNewLine & vbNewLine)
  252.                                 GoTo skip
  253.                             End If
  254.                         Next
  255.                     End If
  256.                 Next
  257.             Catch ex As Exception
  258.                 MsgBox(ex.Message)
  259.                 Return
  260.             End Try
  261.         ElseIf (Twitter_Tweets_Get).ToLower = "usertimeline" Then
  262.             Try
  263.                 Twitter.AuthenticateWith(Twitter_consumerkey, Twitter_consumersecretkey, Twitter_User_Token, Twitter_User_SecretToken)
  264.                 For Each tweet As TwitterStatus In Twitter.UserTimeline
  265.                     If Twitter_Keywords = Nothing = False Then
  266.                         Dim words As String() = (Twitter_Keywords).ToString.ToLower.Split(New Char() {","c})
  267.                         Dim word As String
  268.                         For Each word In words
  269.                             If tweet.Text.ToLower.Replace(" ", Nothing).Contains(word.ToLower) Then
  270.                                 TwitterFeed.AppendText(tweet.User.ScreenName + ": " + tweet.Text & vbNewLine & vbNewLine)
  271.                                 GoTo skip
  272.                             End If
  273.                         Next
  274.                     End If
  275.                 Next
  276.             Catch ex As Exception
  277.                 MsgBox(ex.Message)
  278.                 Return
  279.             End Try
  280.         End If
  281. Skip:
  282.         Try
  283.             Dim lines As String() = Old_Twitter_feed.Lines '<- array create here.
  284.             For i As Integer = 0 To lines.GetUpperBound(0)
  285.                 TwitterFeed.Text = TwitterFeed.Lines(i).Replace(Old_Twitter_feed.Lines(i), Nothing)
  286.             Next i
  287.  
  288.         Catch ex As Exception
  289.  
  290.         End Try
  291.         If TwitterFeed.Text = Nothing = False Then
  292.             If firsttime = 0 Then
  293.                 Old_Twitter_feed.Text = TwitterFeed.Text + Old_Twitter_feed.Text
  294.             End If
  295.         End If
  296.         If firsttime = 1 Then
  297.             firsttime = 0
  298.             Old_Twitter_feed.Text = TwitterFeed.Text
  299.         End If
  300.  
  301.         ' IRC SENDING PART
  302.         If Send_Tweet_over_irc = True Then
  303.             Dim lines As String() = TwitterFeed.Lines '<- array create here.
  304.             For i As Integer = 0 To lines.GetUpperBound(0)
  305.                 If spam_prevention = TwitterFeed.Lines(i) Then
  306.                     Return
  307.                 End If
  308.  
  309.                 If hourly_limitz < Twitter_hourly_limit Then
  310.  
  311.                     If Twitter_Highlight_Keywords = Nothing = False Then
  312.                         Dim words As String() = (Twitter_Highlight_Keywords).ToString.ToLower.Replace(" ", Nothing).Split(New Char() {","c})
  313.                         Dim word As String
  314.                         For Each word In words
  315.                             If TwitterFeed.Lines(i).ToLower.Contains(word) Then
  316.                                 irc.SendMessage(SendType.Message, IRC_CHANNEL, "" & twitter_highlight_color & TwitterFeed.Lines(i))
  317.                                 GoTo skip2
  318.                             End If
  319.                         Next
  320.                     End If
  321.  
  322.                     If Twitter_TweetColor = Nothing Then
  323.                         irc.SendMessage(SendType.Message, IRC_CHANNEL, TwitterFeed.Lines(i))
  324.                     Else
  325.                         irc.SendMessage(SendType.Message, IRC_CHANNEL, "" & Twitter_TweetColor & TwitterFeed.Lines(i))
  326.                     End If
  327. skip2:
  328.  
  329.                     spam_prevention = TwitterFeed.Lines(i)
  330.                     hourly_limitz = hourly_limitz + 1
  331.                 End If
  332.             Next i
  333.         End If
  334.         If first_run = 1 Then
  335.             first_run = 0
  336.             Send_Tweet_over_irc = True
  337.         End If
  338.     End Sub
  339.  
  340.     Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
  341.         Update.Stop()
  342.     End Sub
  343.  
  344.     Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
  345.         Update.Start()
  346.     End Sub
  347.  
  348.     '''' IRC CLIENT
  349.     Private Sub irc_OnConnected(ByVal sender As Object, ByVal e As System.EventArgs)
  350.         irc.Login(IRC_NICKNAME, IRC_DISCRIP)
  351.         irc.Listen(False)
  352.         AddHandler irc.OnChannelMessage, AddressOf irc_OnChannelMessage
  353.         AddHandler irc.OnDisconnected, AddressOf irc_disconnect
  354.         AddHandler irc.OnDisconnecting, AddressOf irc_disconnect
  355.         AddHandler irc.OnConnectionError, AddressOf irc_disconnect
  356.         AddHandler irc.OnJoin, AddressOf irc_OnJoin
  357.         AddHandler irc.OnPart, AddressOf irc_Onpart
  358.         IRC_CONNECTION.RunWorkerAsync()
  359.  
  360.         irc.RfcJoin(IRC_CHANNEL, IRC_CHANNEL_PASSWORD)
  361.            If IRC_CHANNEL_PASSWORD = Nothing = False Then
  362.                 irc.SendMessage(SendType.Message, "nickserv", "idenify " & IRC_Nickserv_Password)
  363.         End If
  364.  
  365.         If IRC_Oper_Username = Nothing = False Then
  366.             If IRC_Oper_Password = Nothing = False Then
  367.                 irc.RfcOper(IRC_Oper_Username, IRC_Oper_Password)
  368.             End If
  369.         End If
  370.  
  371.         If IRC_Rejoin_On_Kick = "1" Then
  372.             irc.AutoRejoinOnKick = True
  373.         End If
  374.  
  375.         Exit Sub
  376. pp:
  377.         Application.Restart()
  378.     End Sub
  379.     Private Sub irc_Onpart(ByVal sender As Object, ByVal e As PartEventArgs)
  380.  
  381.     End Sub
  382.     Private Sub irc_OnJoin(ByVal sender As Object, ByVal e As JoinEventArgs)
  383.  
  384.     End Sub
  385.     Private Sub irc_disconnect(ByVal sender As Object, ByVal e As Meebey.SmartIrc4net.IrcEventArgs)
  386.         If IRC_Restart_On_Disconnection = "1" Then
  387.             Application.Restart()
  388.         End If
  389.     End Sub
  390.     Private Sub irc_OnChannelMessage(ByVal sender As Object, ByVal e As Meebey.SmartIrc4net.IrcEventArgs)
  391.         Dim msg As String = e.Data.Message.ToLower
  392.         If msg = "!stop" Then
  393.             Send_Tweet_over_irc = False
  394.             irc.SendMessage(SendType.Message, IRC_CHANNEL, "Live Twitter Feed Stopped")
  395.         ElseIf msg = "!start" Then
  396.             Send_Tweet_over_irc = True
  397.             irc.SendMessage(SendType.Message, IRC_CHANNEL, "Live Twitter Feed Started")
  398.         End If
  399.         If IRC_CONNECTION.IsBusy = False Then
  400.             IRC_CONNECTION.RunWorkerAsync()
  401.         End If
  402.         If msg = "!about" Then
  403.             irc.SendMessage(SendType.Message, IRC_CHANNEL, "Programmed By: Brandan Tyler Lasley Using TwitterVB2 dll")
  404.         End If
  405.         Exit Sub
  406. PP:
  407.         Application.Restart()
  408.     End Sub
  409.     Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  410.         Send_Tweet_over_irc = True
  411.     End Sub
  412.     Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
  413.         Send_Tweet_over_irc = False
  414.     End Sub
  415.     Private Sub IRC_CONNECTION_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles IRC_CONNECTION.DoWork
  416.         On Error GoTo pp
  417.         While True
  418.             irc.ReadLine(False)
  419.             Threading.Thread.Sleep(100)
  420.         End While
  421.         Exit Sub
  422. pp:
  423.         Application.Restart()
  424.     End Sub
  425. End Class
  426.  
  427. Public Class IniFile
  428.     ' Managed IniFile Class
  429.  
  430. #Region "Private variables"
  431.     ' =======================================================================
  432.     ' Private variables used in the class
  433.  
  434.     Private mFileName As String = ""
  435.     Private mDs As Data.DataSet
  436. #End Region
  437.  
  438. #Region "Contructors"
  439.     ' =======================================================================
  440.     ' Constructors
  441.  
  442.     Public Sub New()
  443.         'Nothing here
  444.     End Sub
  445.  
  446.     Public Sub New(ByVal iniFileName As String)
  447.         ' Open the IniFile
  448.         FileName = iniFileName
  449.     End Sub
  450.  
  451. #End Region
  452.  
  453. #Region "Methodes"
  454.     ' =======================================================================
  455.     ' Methodes
  456.  
  457.     Public Overloads Function ReadString(ByVal section As String, ByVal key As String) As String
  458.         ' Function ReadString Number 1
  459.  
  460.         ' Read string from INI Dataset
  461.  
  462.         ' Use function number 2
  463.         ' Use an empty string as defaultvalue
  464.         Return Me.ReadString(section, key, "")
  465.     End Function
  466.  
  467.     Public Overloads Function ReadString(ByVal section As String, ByVal key As String, ByVal defaultValue As String) As String
  468.         ' Function ReadString Number 2
  469.  
  470.         ' Read string from INI Dataset
  471.         Return Read(section, key, defaultValue)
  472.     End Function
  473.  
  474.     Public Overloads Function ReadString(ByVal section As String, ByVal key As String, ByVal defaultValue As String, ByVal iniFileName As String) As String
  475.         ' Function ReadString Number 3
  476.  
  477.         ' Open the IniFile
  478.         FileName = iniFileName
  479.  
  480.         ' Read string from INI Dataset
  481.  
  482.         ' Use function number 2
  483.         Return Me.ReadString(section, key, defaultValue)
  484.     End Function
  485.  
  486.     Public Overloads Function ReadInteger(ByVal section As String, ByVal key As String) As Integer
  487.         ' Function ReadInteger Number 1
  488.  
  489.         ' Store return value
  490.  
  491.         ' Use function number 2
  492.         ' Use 0 as defaultvalue
  493.         Return Me.ReadInteger(section, key, 0)
  494.     End Function
  495.  
  496.     Public Overloads Function ReadInteger(ByVal section As String, ByVal key As String, ByVal defaultValue As Integer) As Integer
  497.         ' Function ReadInteger Number 2
  498.  
  499.         ' Store return value
  500.         Dim ret As Integer
  501.         Dim tmpRet As String
  502.  
  503.         ' Read string from INI Dataset
  504.         ' First convert DefaultValue to a string to use the Common Read function
  505.         tmpRet = Read(section, key, CType(defaultValue, String))
  506.  
  507.         Try
  508.             ' Convert the Value to an Integer
  509.             ret = CType(tmpRet, Integer)
  510.  
  511.         Catch
  512.             ' When the value couldn't convert to a integer, return zero
  513.             ret = 0
  514.         End Try
  515.  
  516.         Return ret
  517.     End Function
  518.  
  519.     Public Overloads Function ReadInteger(ByVal section As String, ByVal key As String, ByVal defaultValue As Integer, ByVal iniFileName As String) As Integer
  520.         ' Function ReadInteger Number 3
  521.  
  522.         ' Open the IniFile
  523.         FileName = iniFileName
  524.  
  525.         ' Use ReadInteger function number 2
  526.         Return Me.ReadInteger(section, key, defaultValue)
  527.     End Function
  528.  
  529.     Public Function SectionNames() As Collections.ArrayList
  530.         ' Store return value in an arraylist
  531.         Dim ret As New Collections.ArrayList()
  532.  
  533.         Dim table As Data.DataTable
  534.  
  535.         ' Loop through all the Tables
  536.         For Each table In mDs.Tables
  537.             ' Add tablename to the ArrayList
  538.             ret.Add(table.TableName)
  539.         Next
  540.  
  541.         Return ret
  542.     End Function
  543.  
  544.     Public Overloads Sub WriteString(ByVal section As String, ByVal key As String, ByVal value As String)
  545.         ' Function WriteString Number 1
  546.  
  547.         ' Store data in dataset
  548.         Write(section, key, value)
  549.  
  550.         ' Write dataset back to disk
  551.         DumpDatasetToIni()
  552.     End Sub
  553.  
  554.     Public Overloads Sub WriteString(ByVal section As String, ByVal key As String, ByVal value As String, ByVal iniFileName As String)
  555.         ' Function WriteString Number 2
  556.  
  557.         ' Open the IniFile
  558.         FileName = iniFileName
  559.  
  560.         ' Use WriteString function number 1
  561.         Me.WriteString(section, key, value)
  562.     End Sub
  563.  
  564.     Public Overloads Sub WriteInteger(ByVal section As String, ByVal key As String, ByVal value As Integer)
  565.         ' Function WriteInteger Number 1
  566.  
  567.         ' First convert Value to a string to use the WriteString function number 1
  568.         Me.WriteString(section, key, value.ToString)
  569.     End Sub
  570.  
  571.     Public Overloads Sub WriteInteger(ByVal section As String, ByVal key As String, ByVal value As Integer, ByVal iniFileName As String)
  572.         ' Function WriteInteger Number 2
  573.  
  574.         ' First convert Value to a string to use the WriteString function number 2
  575.         Me.WriteString(section, key, value.ToString, iniFileName)
  576.     End Sub
  577.  
  578.     Public Overloads Sub DeleteSection(ByVal section As String)
  579.         ' Function DeleteSection Number 1
  580.  
  581.         ' Delete 'Section' Table from Dataset
  582.         ' First check if section exists
  583.         If Not (mDs.Tables(section) Is Nothing) Then
  584.             ' Section is found, so kill it
  585.             mDs.Tables.Remove(section)
  586.  
  587.             ' Write dataset back to disk
  588.             DumpDatasetToIni()
  589.         End If
  590.     End Sub
  591.  
  592.     Public Overloads Sub DeleteSection(ByVal section As String, ByVal iniFileName As String)
  593.         ' Function DeleteSection Number 2
  594.  
  595.         ' Open the IniFile
  596.         FileName = iniFileName
  597.  
  598.         ' Use DeleteSection function number 1
  599.         Me.DeleteSection(section)
  600.     End Sub
  601. #End Region
  602.  
  603. #Region "Properties"
  604.     ' =======================================================================
  605.     ' Properties
  606.  
  607.     Public Property FileName() As String
  608.         Get
  609.             ' Return Filename
  610.             Return mFileName
  611.         End Get
  612.         Set(ByVal Value As String)
  613.             ' Check if File is allready open
  614.             If Value.Trim <> mFileName Then
  615.                 ' If not, open it
  616.                 mFileName = Value
  617.  
  618.                 LoadIniToDataSet()
  619.             End If
  620.         End Set
  621.     End Property
  622.  
  623.     Public ReadOnly Property DataSet() As Data.DataSet
  624.         Get
  625.             ' Return Dataset
  626.             Return mDs
  627.         End Get
  628.     End Property
  629.  
  630. #End Region
  631.  
  632. #Region "Private Section"
  633.     ' =======================================================================
  634.     ' Private Section
  635.  
  636.     Private Function Read(ByVal section As String, ByVal key As String, ByVal defaultValue As String) As String
  637.         ' Store return value
  638.         Dim ret As String
  639.  
  640.         Try
  641.             ' Section = TableName
  642.             ' Key = ColumnName
  643.             ' Row = 0, because there is only one row for each table
  644.             ' Get the value from the dataset
  645.             ret = mDs.Tables(section).Rows(0).Item(key).ToString
  646.  
  647.         Catch
  648.             ' If the Section or Key isn't found return the DefaultValue
  649.             ret = defaultValue
  650.         End Try
  651.  
  652.         Return ret
  653.     End Function
  654.  
  655.     Private Sub Write(ByVal section As String, ByVal key As String, ByVal value As String)
  656.         ' Section = Table
  657.         ' Key = Column
  658.         ' Row = 0, because there is only one row for each table
  659.  
  660.         ' Look for section in Dataset
  661.         If (mDs.Tables(section) Is Nothing) Then
  662.             ' Section is not found
  663.             ' Add section to the dataset
  664.             mDs.Tables.Add(section)
  665.  
  666.             ' Add Key to Section
  667.             mDs.Tables(section).Columns.Add(key)
  668.  
  669.             ' We must add a new row to the dataset
  670.             Dim row As Data.DataRow
  671.             row = mDs.Tables(section).NewRow
  672.  
  673.             ' Add Value to Key
  674.             row.Item(key) = value
  675.             mDs.Tables(section).Rows.Add(row)
  676.  
  677.         Else
  678.             ' Section was found, now look for key in section
  679.             If (mDs.Tables(section).Columns(key) Is Nothing) Then
  680.                 ' Key is not found
  681.                 ' Add key to the section
  682.                 mDs.Tables(section).Columns.Add(key)
  683.             End If
  684.  
  685.             ' Update Value for key
  686.             mDs.Tables(section).Rows(0).Item(key) = value
  687.  
  688.         End If
  689.     End Sub
  690.  
  691.     Private Overloads Sub LoadIniToDataSet()
  692.         ' Initialise Dataset
  693.         mDs = New Data.DataSet()
  694.  
  695.         ' Open the File
  696.         Dim file As New IO.FileInfo(mFileName)
  697.  
  698.         ' Create DatasetName from IniFileName by removing the file extention
  699.         mDs.DataSetName = file.Name.Remove(file.Name.IndexOf(file.Extension), file.Extension.Length)
  700.  
  701.         ' Check if inifile exists on specified path
  702.         If file.Exists() Then
  703.             ' Store each Section as a Table in the Dataset
  704.             Dim table As Data.DataTable
  705.  
  706.             ' Define row to fill with KeyValue
  707.             Dim row As Data.DataRow
  708.  
  709.             ' A switch to keep track when we have add the row to the table
  710.             Dim addRow As Boolean = False
  711.  
  712.             ' A switch to keep track when we have add the row to the table
  713.             Dim skipSection As Boolean = False
  714.  
  715.             ' Use a filestream to read the IniFile
  716.             Dim fileStream As New IO.StreamReader(mFileName)
  717.             Dim readLine As String
  718.  
  719.             ' Read the first line
  720.             readLine = fileStream.ReadLine
  721.  
  722.             ' Loop to the end of the File
  723.             Do While Not (readLine Is Nothing)
  724.                 ' Trim all leading en ending spaces
  725.                 readLine = readLine.Trim()
  726.  
  727.                 ' Skip empty lines and commented lines
  728.                 If readLine <> "" And Not readLine.StartsWith(";") Then
  729.  
  730.                     ' Check if the line is a Section Header
  731.                     If readLine.StartsWith("[") AndAlso readLine.EndsWith("]") Then
  732.                         ' A new Section means a new Table
  733.  
  734.                         ' Before we create a new table
  735.                         ' add all the values to the previous created table
  736.                         If addRow Then
  737.                             table.Rows.Add(row)
  738.                         End If
  739.  
  740.                         ' remove brackets from readline
  741.                         readLine = readLine.TrimStart("["c)
  742.                         readLine = readLine.TrimEnd("]"c)
  743.  
  744.                         ' Tablename is SectionName
  745.                         ' Check if table allready exists
  746.                         ' If so, skip the rest of the section
  747.                         ' An iniFile can't have double sections
  748.  
  749.                         ' First set it to True, will be corrected a few lines below
  750.                         skipSection = True
  751.  
  752.                         table = mDs.Tables(readLine)
  753.                         If (table Is Nothing) Then
  754.                             ' If not, Create new table
  755.                             table = New Data.DataTable(readLine)
  756.  
  757.                             ' Add Table to Dataset
  758.                             mDs.Tables.Add(table)
  759.  
  760.                             ' Adds a new row to the table
  761.                             row = table.NewRow
  762.  
  763.                             skipSection = False
  764.                         End If
  765.  
  766.                         ' Clear switch
  767.                         addRow = False
  768.                     Else
  769.  
  770.                         If Not skipSection Then
  771.  
  772.                             ' Use a string array to store data
  773.                             Dim splitLine() As String
  774.  
  775.                             ' Split the line by a =
  776.                             ' SplitDate(0) holds the Key
  777.                             ' SplitDate(1) holds the KeyValue
  778.                             splitLine = readLine.Split("="c)
  779.  
  780.                             ' Columnname is Key
  781.                             ' Check if Key allready exists
  782.                             ' if so Skip it, a section can't have double keys
  783.                             If (table.Columns(splitLine(0)) Is Nothing) Then
  784.                                 ' Add Key as a new column to the table
  785.                                 table.Columns.Add(Trim(splitLine(0)))
  786.  
  787.                                 ' Check if line is splitted ok
  788.                                 If splitLine.Length = 2 Then
  789.                                     ' Fill Key-column with KeyValue
  790.                                     row.Item(Trim(splitLine(0))) = Trim(splitLine(1))
  791.  
  792.                                 Else
  793.                                     ' Fill Key-column with empty string
  794.                                     row.Item(splitLine(0)) = ""
  795.  
  796.                                 End If
  797.  
  798.                                 ' Set switch for adding row
  799.                                 addRow = True
  800.                             End If
  801.  
  802.                         End If
  803.                     End If
  804.                 End If
  805.  
  806.                 ' Read next Line
  807.                 readLine = fileStream.ReadLine
  808.             Loop
  809.  
  810.             ' Don't forget the last entries
  811.             If addRow Then
  812.                 table.Rows.Add(row)
  813.             End If
  814.  
  815.             ' Close file
  816.             fileStream.Close()
  817.  
  818.         End If
  819.     End Sub
  820.  
  821.     Private Sub DumpDatasetToIni()
  822.         ' Check if inifile exists on specified path
  823.         If IO.File.Exists(mFileName) Then
  824.             ' if, so....delete it
  825.             IO.File.Delete(mFileName)
  826.         End If
  827.  
  828.         ' Use a StreamWriter to make a new inifile
  829.         Dim file As IO.StreamWriter = IO.File.CreateText(mFileName)
  830.  
  831.         ' Section = TableName
  832.         ' Key = ColumnName
  833.         ' Row = 0, because there is only one row for each table
  834.         Dim table As Data.DataTable
  835.         Dim col As Data.DataColumn
  836.         Dim value As String
  837.  
  838.         ' Loop through all sections
  839.         For Each table In mDs.Tables
  840.             ' Write section name
  841.             file.WriteLine("[" & table.TableName & "]")
  842.  
  843.             ' Loop through all key's in section
  844.             For Each col In table.Columns
  845.                 ' Find value for key
  846.                 value = table.Rows(0).Item(col).ToString
  847.  
  848.                 ' Write Key and Value
  849.                 file.WriteLine(col.ColumnName & "=" & value)
  850.             Next
  851.  
  852.             ' Make an empty line between the sections
  853.             file.WriteLine("")
  854.         Next
  855.  
  856.         ' Close IniFile
  857.         file.Close()
  858.  
  859.     End Sub
  860.  
  861. #End Region
  862.  
  863. End Class
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement