'Update RSS Feed
'Copyright (c) 2014 State of Vermont Legislative Joint Fiscal Office.
'Licensed under the Apache License, Version 2.0 (the "License");
'you may not use this file except in compliance with the License.
'You may obtain a copy of the License at
 '      			
'http://www.apache.org/licenses/LICENSE-2.0
'
'Unless required by applicable law or agreed to in writing, software
'distributed under the License is distributed on an "AS IS" BASIS,
'WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
'See the License for the specific language governing permissions and
'limitations under the License.	
'

Imports System.IO
Imports System.Text.RegularExpressions
Imports System.Net
Imports System.Threading

Public Class frmMain

    Private Sub btnOpenRSSFeed_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOpenRSSFeed.Click
        System.Diagnostics.Process.Start("C:\YourRSSLocation")
    End Sub

    Private Sub btnOpenJFOHome_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOpenJFOHome.Click
        System.Diagnostics.Process.Start("iexplore.exe", "YourWebsiteURL")
    End Sub

    Private Sub btnAddToRSSFeed_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddToRSSFeed.Click
        UpdateRSS()
    End Sub

    Private Sub UpdateRSS()

        Dim strTitle As String
        Dim strDate As String
        Dim strHyperlink As String
        Dim blnInputsValid As Boolean
        Dim strRegMatchDate As String
        Dim intOkCancel As Integer

        Dim fs As FileStream
        Dim sReader As StreamReader
        Dim sWriter As StreamWriter
        Dim fileReadLine As String
        Dim fileRead As String
        Dim fileReadEnd As String
        Const strRSSFileConstant As String = "C:\YourRSSfile.xml"
        Const strUploadDirectory As String = "ftp://example.com"

        strTitle = Me.txtTitle.Text
        strDate = Me.txtDate.Text
        strHyperlink = Me.txtHyperlink.Text

        'Check to make sure there is a title for the RSS item
        If strTitle = "" Then
            MsgBox("You must provide a title for the RSS feed")
            blnInputsValid = False
        Else
            blnInputsValid = True
        End If

        'Matches a date in the format MM/dd/yyyy
        strRegMatchDate = "\d{2}/\d{2}/\d{4}"
        'Check to make sure there is a date for the RSS item
        If strDate = "" Then
            MsgBox("You must enter the date that the document is being posted on")
            blnInputsValid = False
        Else
            If Regex.IsMatch(strDate, strRegMatchDate) Then
                blnInputsValid = True
            Else
                MsgBox("The date must be in the format mm/dd/yyyy")
                blnInputsValid = False
            End If
        End If

        'Check to make sure a hyperlink to the document was provided for the RSS item, and that the http:// or https:// or ftp:// is included
        If strHyperlink = "" Then
            MsgBox("You must provide a hyperlink to the document that was posted")
            blnInputsValid = False
        ElseIf strHyperlink.Substring(0, 7) <> "http://" Then
            If strHyperlink.Substring(0, 6) <> "ftp://" Then
                If strHyperlink.Substring(0, 8) <> "https://" Then
                    MsgBox("Invalid Hyperlink: You did not provide the http:// prefix before the web address in the 'Hyperlink' field (you also did not provide an https:// or ftp:// prefix, though these last two protocols are generally not used on our site)")
                    blnInputsValid = False
                Else
                    intOkCancel = MsgBox("You provided an https:// prefix, which is generally not used on our website.  Select 'OK' to continue, or select 'Cancel' to go back and double-check the hyperlink address.", MsgBoxStyle.OkCancel)
                    If intOkCancel = vbCancel Then
                        blnInputsValid = False
                        Exit Sub
                    Else
                        blnInputsValid = True
                    End If
                End If
            Else
                intOkCancel = MsgBox("You provided an ftp:// prefix, which is generally not used on our website.  Select 'OK' to continue, or select 'Cancel' to go back and double-check the hyperlink address.", MsgBoxStyle.OkCancel)
                If intOkCancel = vbCancel Then
                    blnInputsValid = False
                    Exit Sub
                Else
                    blnInputsValid = True
                End If
            End If
        Else
            blnInputsValid = True
        End If

        'Exit the subroutine if one of the fields is empty or invalid
        If blnInputsValid = False Then Exit Sub

        strTitle = FixXMLEntities(strTitle)
        strHyperlink = FixXMLEntities(strHyperlink)

        fileRead = ""
        fileReadEnd = ""

        Try
            fs = File.Open(strRSSFileConstant, FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read)
            sReader = New StreamReader(fs)

            'Initialize the read line and read [mupltiple lines] variables
            fileReadLine = sReader.ReadLine & Chr(13)
            fileRead = ""

            'Read the top of file up until items appear
            While (InStr(fileReadLine, "") = 0 And sReader.EndOfStream = False)
                fileRead += fileReadLine

                fileReadLine = sReader.ReadLine & Chr(13)
            End While

            'grab the first  tag and start the footer section with it
            fileReadEnd = fileReadLine

            'Read the rest of the file
            While (sReader.EndOfStream = False)
                fileReadLine = sReader.ReadLine & Chr(13)
                fileReadEnd += fileReadLine
            End While

            sReader.Close()
            sReader = Nothing

            fs.Close()
            fs = Nothing

        Catch errFileRead As Exception
            MsgBox("Error reading the RSS feed XML file - Program will now exit (see details below)" & Chr(13) & errFileRead.Message)
            Me.Close()
        End Try

        Try

            File.Create(strRSSFileConstant).Close()

            fs = File.Open(strRSSFileConstant, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read)
            sWriter = New StreamWriter(fs)

            'Write the header to the file
            sWriter.Write(fileRead)

            'Write the new item to the file
            sWriter.Write(Chr(9) & Chr(9) & "" & Chr(13))
            sWriter.Write(Chr(9) & Chr(9) & Chr(9) & "" & strTitle & "" & Chr(13))
            sWriter.Write(Chr(9) & Chr(9) & Chr(9) & "" & strDate & "" & Chr(13))
            sWriter.Write(Chr(9) & Chr(9) & Chr(9) & "" & strHyperlink & "" & Chr(13))
            sWriter.Write(Chr(9) & Chr(9) & "" & Chr(13))

            'Write the footer to the file
            sWriter.Write(fileReadEnd)

            'Close out the write stream and the file stream
            sWriter.Close()
            sWriter = Nothing
            fs.Close()
            fs = Nothing

            Me.txtTitle.Text = ""
            Me.txtHyperlink.Text = ""
            MsgBox("Item successfully added to RSS feed")



            UploadRSS(strUploadDirectory, strRSSFileConstant)

        Catch errFileRead As Exception
            MsgBox("Error writing to the RSS feed XML file - Program will now exit (see details below)" & Chr(13) & errFileRead.Message)
            Me.Close()
        End Try

    End Sub

    Private Sub frmMain_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'Automatically fill in date textbox with today's date
        Me.txtDate.Text = Format(Now(), "MM/dd/yyyy")
        Me.txtHyperlink.Text = ""
    End Sub

    'TODO: implement some RegEx code to replace invalid XML characters with their entities
    Private Function FixXMLEntities(strInput As String) As String
        'The final output string
        Dim strOutput As String
        strOutput = strInput

        'Regular Expressions Patterns
        'Check for quotes
        Dim strQuote As String
        strQuote = Chr(34)
        'Check for single quotes
        Dim strApos As String
        strApos = "'"
        'Check for less than (angle bracket)
        Dim strLT As String
        strLT = "<"
        'Check for less than (angle bracket)
        Dim strGT As String
        strGT = ">"
        'Check for an ampersand that's not an entity
        Dim strAmp As String
        strAmp = "&(?!(amp;|quot;|apos;|lt;|gt;))"

        strOutput = Regex.Replace(strOutput, strQuote, """)
        strOutput = Regex.Replace(strOutput, strApos, "'")
        strOutput = Regex.Replace(strOutput, strLT, "<")
        strOutput = Regex.Replace(strOutput, strGT, ">")
        strOutput = Regex.Replace(strOutput, strAmp, "&") ', RegexOptions.RightToLeft)


        Return strOutput
    End Function

    Sub UploadRSS(uriString, fileName)
        ' Create a new WebClient instance. 
        Dim myWebClient As New WebClient()

		'add your FTP credentials here
        myWebClient.Credentials = New NetworkCredential("username", "password")


        ' Upload the file to the URI. 
        Dim responseArray As Byte() = myWebClient.UploadFile(uriString, fileName)

    End Sub

End Class

  		  		
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
'Update RSS Feed - Windows Form
'Copyright (c) 2014 State of Vermont Legislative Joint Fiscal Office.
'Licensed under the Apache License, Version 2.0 (the "License");
'you may not use this file except in compliance with the License.
'You may obtain a copy of the License at
 '      			
'http://www.apache.org/licenses/LICENSE-2.0
'
'Unless required by applicable law or agreed to in writing, software
'distributed under the License is distributed on an "AS IS" BASIS,
'WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
'See the License for the specific language governing permissions and
'limitations under the License.	
'
'
Partial Class frmMain
    Inherits System.Windows.Forms.Form

    'Form overrides dispose to clean up the component list.
    <System.Diagnostics.DebuggerNonUserCode()> _
    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
        Try
            If disposing AndAlso components IsNot Nothing Then
                components.Dispose()
            End If
        Finally
            MyBase.Dispose(disposing)
        End Try
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    <System.Diagnostics.DebuggerStepThrough()> _
    Private Sub InitializeComponent()
        Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(frmMain))
        Me.lblTitle = New System.Windows.Forms.Label()
        Me.lblDate = New System.Windows.Forms.Label()
        Me.lblHyperlink = New System.Windows.Forms.Label()
        Me.txtTitle = New System.Windows.Forms.TextBox()
        Me.txtDate = New System.Windows.Forms.TextBox()
        Me.txtHyperlink = New System.Windows.Forms.TextBox()
        Me.lblAboutDate = New System.Windows.Forms.Label()
        Me.btnAddToRSSFeed = New System.Windows.Forms.Button()
        Me.btnOpenRSSFeed = New System.Windows.Forms.Button()
        Me.btnOpenJFOHome = New System.Windows.Forms.Button()
        Me.SuspendLayout()
        '
        'lblTitle
        '
        Me.lblTitle.AutoSize = True
        Me.lblTitle.Font = New System.Drawing.Font("Arial", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.lblTitle.Location = New System.Drawing.Point(10, 18)
        Me.lblTitle.Name = "lblTitle"
        Me.lblTitle.Size = New System.Drawing.Size(32, 16)
        Me.lblTitle.TabIndex = 0
        Me.lblTitle.Text = "Title"
        '
        'lblDate
        '
        Me.lblDate.AutoSize = True
        Me.lblDate.Font = New System.Drawing.Font("Arial", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.lblDate.Location = New System.Drawing.Point(10, 56)
        Me.lblDate.Name = "lblDate"
        Me.lblDate.Size = New System.Drawing.Size(40, 16)
        Me.lblDate.TabIndex = 1
        Me.lblDate.Text = "Date*"
        '
        'lblHyperlink
        '
        Me.lblHyperlink.AutoSize = True
        Me.lblHyperlink.Font = New System.Drawing.Font("Arial", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.lblHyperlink.Location = New System.Drawing.Point(10, 94)
        Me.lblHyperlink.Name = "lblHyperlink"
        Me.lblHyperlink.Size = New System.Drawing.Size(62, 16)
        Me.lblHyperlink.TabIndex = 2
        Me.lblHyperlink.Text = "Hyperlink"
        '
        'txtTitle
        '
        Me.txtTitle.Location = New System.Drawing.Point(91, 17)
        Me.txtTitle.Name = "txtTitle"
        Me.txtTitle.Size = New System.Drawing.Size(321, 20)
        Me.txtTitle.TabIndex = 3
        '
        'txtDate
        '
        Me.txtDate.Location = New System.Drawing.Point(90, 53)
        Me.txtDate.Name = "txtDate"
        Me.txtDate.Size = New System.Drawing.Size(322, 20)
        Me.txtDate.TabIndex = 4
        '
        'txtHyperlink
        '
        Me.txtHyperlink.Location = New System.Drawing.Point(89, 89)
        Me.txtHyperlink.Name = "txtHyperlink"
        Me.txtHyperlink.Size = New System.Drawing.Size(323, 20)
        Me.txtHyperlink.TabIndex = 5
        '
        'lblAboutDate
        '
        Me.lblAboutDate.AutoSize = True
        Me.lblAboutDate.Font = New System.Drawing.Font("Arial", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.lblAboutDate.Location = New System.Drawing.Point(10, 131)
        Me.lblAboutDate.Name = "lblAboutDate"
        Me.lblAboutDate.Size = New System.Drawing.Size(276, 16)
        Me.lblAboutDate.TabIndex = 6
        Me.lblAboutDate.Text = "* Format the date as mm/dd/yyyy or mm/yyyy"
        '
        'btnAddToRSSFeed
        '
        Me.btnAddToRSSFeed.Font = New System.Drawing.Font("Arial", 12.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.btnAddToRSSFeed.Location = New System.Drawing.Point(130, 158)
        Me.btnAddToRSSFeed.Name = "btnAddToRSSFeed"
        Me.btnAddToRSSFeed.Size = New System.Drawing.Size(156, 43)
        Me.btnAddToRSSFeed.TabIndex = 7
        Me.btnAddToRSSFeed.Text = "Add To RSS Feed"
        Me.btnAddToRSSFeed.UseVisualStyleBackColor = True
        '
        'btnOpenRSSFeed
        '
        Me.btnOpenRSSFeed.Font = New System.Drawing.Font("Arial", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.btnOpenRSSFeed.Location = New System.Drawing.Point(8, 170)
        Me.btnOpenRSSFeed.Name = "btnOpenRSSFeed"
        Me.btnOpenRSSFeed.Size = New System.Drawing.Size(109, 23)
        Me.btnOpenRSSFeed.TabIndex = 8
        Me.btnOpenRSSFeed.Text = "Open RSS Feed"
        Me.btnOpenRSSFeed.UseVisualStyleBackColor = True
        '
        'btnOpenJFOHome
        '
        Me.btnOpenJFOHome.Font = New System.Drawing.Font("Arial", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.btnOpenJFOHome.Location = New System.Drawing.Point(320, 158)
        Me.btnOpenJFOHome.Name = "btnOpenJFOHome"
        Me.btnOpenJFOHome.Size = New System.Drawing.Size(72, 43)
        Me.btnOpenJFOHome.TabIndex = 9
        Me.btnOpenJFOHome.Text = "Open JFO Homepage"
        Me.btnOpenJFOHome.UseVisualStyleBackColor = True
        '
        'frmMain
        '
        Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
        Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
        Me.ClientSize = New System.Drawing.Size(423, 216)
        Me.Controls.Add(Me.btnOpenJFOHome)
        Me.Controls.Add(Me.btnOpenRSSFeed)
        Me.Controls.Add(Me.btnAddToRSSFeed)
        Me.Controls.Add(Me.lblAboutDate)
        Me.Controls.Add(Me.txtHyperlink)
        Me.Controls.Add(Me.txtDate)
        Me.Controls.Add(Me.txtTitle)
        Me.Controls.Add(Me.lblHyperlink)
        Me.Controls.Add(Me.lblDate)
        Me.Controls.Add(Me.lblTitle)
        Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon)
        Me.Name = "frmMain"
        Me.Text = "Update RSS Feed"
        Me.ResumeLayout(False)
        Me.PerformLayout()

    End Sub
    Friend WithEvents lblTitle As System.Windows.Forms.Label
    Friend WithEvents lblDate As System.Windows.Forms.Label
    Friend WithEvents lblHyperlink As System.Windows.Forms.Label
    Friend WithEvents txtTitle As System.Windows.Forms.TextBox
    Friend WithEvents txtDate As System.Windows.Forms.TextBox
    Friend WithEvents txtHyperlink As System.Windows.Forms.TextBox
    Friend WithEvents lblAboutDate As System.Windows.Forms.Label
    Friend WithEvents btnAddToRSSFeed As System.Windows.Forms.Button
    Friend WithEvents btnOpenRSSFeed As System.Windows.Forms.Button
    Friend WithEvents btnOpenJFOHome As System.Windows.Forms.Button

End Class