SearchEngineWithFaroo.vb

Click To View Text-Only Version


CODE
 

Option Strict On

Option Explicit On

 

Public Class Form1

 

   Private Enum SearchType

       Web

       News

   End Enum

 

   Private Class SearchResult

       Public Title As String = "--"

       Public URL As String = "--"

       Public Domain As String = "--"

       Public ImageURL As String = "--"

       Public PublishDateTime As DateTime

       Public Overview As String = "--"

       Public IsNews As Boolean

   End Class

 

   Private Class UserSearch

       Public SearchTerm As String = "--"

       Public SearchType As SearchType

   End Class

 

   Private currentSearchResults As New List(Of SearchResult)

   Private userCancel As Boolean = False

   Private bgwError As String = ""

 

 

 

   Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) _

       Handles MyBase.Load

 

       With bgw_GetResults

           .WorkerReportsProgress = True

           .WorkerSupportsCancellation = True

       End With

 

       lbl_StatusLeft.Text = ""

       lbl_Overview.Text = ""

       lbl_Navigator.Text = ""

 

       With ProgressBar_Status

           .Minimum = 0

           .Maximum = 100

           .Visible = False

       End With

 

       btn_Search.Enabled = False

       btn_OpenURL.Enabled = False

 

       With PictureBox1

           .SizeMode = PictureBoxSizeMode.Zoom

           .Image = Nothing

       End With

 

       Panel1.Visible = False

 

   End Sub

 

 

 

   Private Sub TextBox_SearchTerm_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) _

       Handles TextBox_SearchTerm.TextChanged

 

       Panel1.Visible = False

 

       If TextBox_SearchTerm.Text.Trim <> "" Then

           btn_Search.Enabled = True

       Else

           btn_Search.Enabled = False

       End If

 

   End Sub

 

 

 

   Private Sub RadioButtons_Click(ByVal sender As Object, ByVal e As System.EventArgs) _

       Handles RadioButton_WebSearch.Click, RadioButton_NewsSearch.Click

 

       Panel1.Visible = False

 

       With TextBox_SearchTerm

           .SelectAll()

           .Focus()

       End With

 

       If TextBox_SearchTerm.Text.Trim <> "" Then

           btn_Search.Enabled = True

       End If

 

   End Sub

 

 

 

   Private Sub btn_Search_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _

       Handles btn_Search.Click

 

       currentSearchResults.Clear()

       RadioButton_WebSearch.Enabled = False

       RadioButton_NewsSearch.Enabled = False

       TextBox_SearchTerm.Enabled = False

       Panel1.Visible = False

 

       If btn_Search.Text = "Search" Then

           lbl_StatusLeft.Text = "Searching..."

 

           With ProgressBar_Status

               .Value = 0

               .Visible = True

           End With

 

           Me.Refresh()

 

           userCancel = False

           bgwError = ""

           Dim thisSearch As New UserSearch

 

           With thisSearch

               .SearchTerm = TextBox_SearchTerm.Text.Trim

 

               If RadioButton_WebSearch.Checked Then

                   .SearchType = SearchType.Web

               Else

                   .SearchType = SearchType.News

               End If

           End With

 

           bgw_GetResults.RunWorkerAsync(thisSearch)

 

           btn_Search.Text = "Cancel"

       Else

           userCancel = True

 

           With btn_Search

               .Text = "Search"

               .Enabled = False

           End With

 

           lbl_StatusLeft.Text = "Cancelling Operation..."

           Me.Refresh()

       End If

 

   End Sub

 

 

 

   Private Sub DataGridView1_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) _

      Handles DataGridView1.SelectionChanged

 

       With PictureBox1

           .SizeMode = PictureBoxSizeMode.CenterImage

           .Image = My.Resources.faroo_attribution

           .Refresh()

       End With

 

       If DataGridView1.SelectedRows.Count = 1 Then

           Dim rowNum As Integer = DataGridView1.CurrentRow.Index

 

           If rowNum > -1 Then

               Dim title As String = DataGridView1.Rows(rowNum).Cells(1).Value.ToString

               Dim qry = From sr As SearchResult In currentSearchResults Where sr.Title = title

 

               If qry.Count = 1 Then

                   lbl_Overview.Text = qry.First.Overview

 

                   If qry.First.ImageURL.StartsWith("http://") Then

                       With PictureBox1

                           .SizeMode = PictureBoxSizeMode.Zoom

                           .ImageLocation = qry.First.ImageURL

                       End With

                   Else

                       With PictureBox1

                           .SizeMode = PictureBoxSizeMode.CenterImage

                           .Image = My.Resources.faroo_attribution

                       End With

                   End If

 

                   If qry.First.URL.StartsWith("http://") Then

                       btn_OpenURL.Enabled = True

                   Else

                       btn_OpenURL.Enabled = False

                   End If

               Else

                   With PictureBox1

                       .SizeMode = PictureBoxSizeMode.CenterImage

                       .Image = My.Resources.faroo_attribution

                   End With

 

                   btn_OpenURL.Enabled = False

                   lbl_Overview.Text = ""

               End If

           End If

       End If

 

   End Sub

 

 

 

   Private Sub btn_OpenURL_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _

       Handles btn_OpenURL.Click

 

       With btn_OpenURL

           .Enabled = False

           .Refresh()

       End With

 

       If DataGridView1.SelectedRows.Count = 1 Then

           Dim rowNum As Integer = DataGridView1.CurrentRow.Index

 

           If rowNum > -1 Then

               Dim title As String = DataGridView1.Rows(rowNum).Cells(1).Value.ToString

               Dim qry = From sr As SearchResult In currentSearchResults Where sr.Title = title

 

               Try

                   Process.Start(qry.First.URL)

 

               Catch ex As Exception

                   MessageBox.Show("An error occurred:" & vbCrLf & vbCrLf & ex.Message, _

                                   "Program Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)

               End Try

           End If

       End If

   End Sub

 

 

 

   Private Sub bgw_GetResults_DoWork(ByVal sender As System.Object, _

                                     ByVal e As System.ComponentModel.DoWorkEventArgs) _

                                     Handles bgw_GetResults.DoWork

 

       Try

           Dim resultList As New List(Of SearchResult)

           Dim thisSearch As New UserSearch

           thisSearch = DirectCast(e.Argument, UserSearch)

 

           Dim hitCount As Integer = FindTotalResults(thisSearch.SearchTerm, _

                                                      thisSearch.SearchType)

 

           If userCancel Then

               bgw_GetResults.CancelAsync()

               Exit Sub

           Else

               If hitCount = -1 Then

                   Stop

               Else

                   If userCancel Then

                       bgw_GetResults.CancelAsync()

                       Exit Sub

                   Else

                       bgw_GetResults.ReportProgress(50)

 

                       resultList = GetResults(thisSearch.SearchTerm, _

                                               thisSearch.SearchType, _

                                               hitCount)

 

                       If thisSearch.SearchType = SearchType.Web Then

                           Dim findNoNews = From sr As SearchResult In resultList Where Not sr.IsNews

                           resultList = findNoNews.ToList

                       Else

                           Dim findNews = From sr As SearchResult In resultList Where sr.IsNews

                           resultList = findNews.ToList

                       End If

 

                       bgw_GetResults.ReportProgress(100)

 

                       If resultList Is Nothing Then

                           Throw New Exception("An error was returned attempting to query" & vbCrLf & _

                                               "the search engine server.")

                       Else

                           e.Result = resultList

                       End If

                   End If

               End If

           End If

 

       Catch ex As Exception

           bgwError = ex.Message

           bgw_GetResults.CancelAsync()

           Exit Sub

       End Try

 

   End Sub

 

 

 

   Private Sub bgw_GetResults_ProgressChanged(ByVal sender As Object, _

                                              ByVal e As System.ComponentModel.ProgressChangedEventArgs) _

                                              Handles bgw_GetResults.ProgressChanged

 

       ProgressBar_Status.Value = e.ProgressPercentage

 

   End Sub

 

 

 

   Private Sub bgw_GetResults_RunWorkerCompleted(ByVal sender As Object, _

                                                 ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) _

                                                 Handles bgw_GetResults.RunWorkerCompleted

 

       RadioButton_WebSearch.Enabled = True

       RadioButton_NewsSearch.Enabled = True

       TextBox_SearchTerm.Enabled = True

       lbl_StatusLeft.Text = ""

       ProgressBar_Status.Visible = False

 

       With btn_Search

           .Text = "Search"

           .Enabled = False

       End With

 

       If bgwError <> "" Then

           MessageBox.Show("An error occurred:" & vbCrLf & vbCrLf & bgwError, _

                           "Program Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)

 

       ElseIf userCancel Then

           lbl_StatusLeft.Text = "Operation Cancelled"

           btn_Search.Enabled = True

 

       Else

           If e.Result IsNot Nothing Then

               currentSearchResults = DirectCast(e.Result, List(Of SearchResult))

 

               lbl_StatusLeft.Text = "Building The Data Grid (" & _

                   currentSearchResults.Count.ToString("n0") & " Results Returned)..."

 

               PopulateDGV(currentSearchResults)

 

               With TextBox_SearchTerm

                   .SelectAll()

                   .Focus()

               End With

           End If

       End If

 

   End Sub

 

 

 

   Private Sub PopulateDGV(ByVal resultList As List(Of SearchResult))

 

       DataGridView1.DataSource = Nothing

       BindingNavigator1.BindingSource = Nothing

 

       Dim dt As New DataTable

       Dim column As New DataColumn

 

 

       With column

           .DataType = System.Type.GetType("System.DateTime")

           .ColumnName = "Publish Date / Time"

           dt.Columns.Add(column)

       End With

 

       column = New DataColumn

 

       With column

           .DataType = System.Type.GetType("System.String")

           .ColumnName = "Title"

           dt.Columns.Add(column)

       End With

 

       Dim row As DataRow

 

       For Each dr As SearchResult In resultList

           row = dt.NewRow

           row("Publish Date / Time") = dr.PublishDateTime

           row("Title") = dr.Title

           dt.Rows.Add(row)

       Next

 

       Dim bs As New BindingSource

       bs.DataSource = dt

 

       With BindingNavigator1

           .BindingSource = bs

           .Enabled = True

       End With

 

       With DataGridView1

           .DataSource = bs

           .Enabled = True

           .MultiSelect = False

           .SelectionMode = DataGridViewSelectionMode.FullRowSelect

           .AlternatingRowsDefaultCellStyle.BackColor = Color.LightBlue

           .Columns(0).Width = 120

           .Columns(0).DefaultCellStyle.Format = "MM/dd/yy hh:mm tt"

           .Columns(1).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill

           .FirstDisplayedCell = .CurrentCell

       End With

 

       If RadioButton_WebSearch.Checked Then

           lbl_Navigator.Text = "Search Type: Web"

       Else

           lbl_Navigator.Text = "Search Type: News"

       End If

 

       With PictureBox1

           .SizeMode = PictureBoxSizeMode.CenterImage

           .Image = My.Resources.faroo_attribution

       End With

 

       Panel1.Visible = True

       lbl_StatusLeft.Text = ""

 

       If DataGridView1.Rows.Count > 0 Then

           DataGridView1.Rows(0).Selected = True

       End If

 

   End Sub

 

 

 

   Private Function FindTotalResults(ByVal searchTerm As String, _

                                     ByVal searchType As SearchType) _

                                     As Integer

 

       Threading.Thread.Sleep(1000)

 

       Dim retVal As Integer = 0

       Dim url As String = ""

 

       If searchType = Form1.SearchType.Web Then

           url = "http://www.faroo.com/instant.xml?q=" & searchTerm & _

                 "&start=1&length=1&l=en&src=web"

       Else

           url = "http://www.faroo.com/instant.xml?q=" & searchTerm & _

                 "&start=1&length=1&l=en&src=news"

       End If

 

       Try

           Dim hitInfo = XElement.Load(url)

 

           If hitInfo IsNot Nothing Then

               If Not Integer.TryParse(hitInfo...<count>.Value, retVal) Then

                   Throw New Exception("No Count Returned")

               End If

           Else

               Throw New Exception("Invalid URL")

           End If

 

       Catch ex As Exception

           retVal = -1

       End Try

 

       Return retVal

 

   End Function

 

 

 

   Private Function GetResults(ByVal searchTerm As String, _

                               ByVal searchType As SearchType, _

                               ByVal searchQty As Integer) _

                               As List(Of SearchResult)

 

       Threading.Thread.Sleep(1000)

 

       Dim retVal As New List(Of SearchResult)

       Dim url As String = ""

 

       If searchType = Form1.SearchType.Web Then

           url = "http://www.faroo.com/instant.xml?q=" & searchTerm & _

                "&start=1&length=" & searchQty.ToString & "&l=en&src=web"

       Else

           url = "http://www.faroo.com/instant.xml?q=" & searchTerm & _

               "&start=1&length=" & searchQty.ToString & "&l=en&src=news"

       End If

 

       Try

           Dim resultInfo = XElement.Load(url)

 

           If resultInfo IsNot Nothing Then

               For Each findResults As XElement In resultInfo...<result>

                   Dim thisSearchResult As New SearchResult

                   Dim allValuesGood As Boolean = True

 

                   With thisSearchResult

                       .Title = findResults...<title>.Value

                       .URL = findResults...<url>.Value

                       .Domain = findResults...<domain>.Value

                       .ImageURL = findResults...<imageUrl>.Value

 

                       If Not Date.TryParse(findResults...<firstPublished>.Value, _

                                            .PublishDateTime) Then

 

                           allValuesGood = False

                       End If

 

                       .Overview = findResults...<kwic>.Value

 

                       If Not Boolean.TryParse(findResults...<isNews>.Value, .IsNews) Then

                           allValuesGood = False

                       End If

                   End With

 

                   If allValuesGood Then

                       retVal.Add(thisSearchResult)

                   End If

               Next

           Else

               Throw New Exception("Invalid URL")

           End If

 

       Catch ex As Exception

           retVal = Nothing

       End Try

 

       Return retVal

 

   End Function

 

 

 

   Private Delegate Function FindTotalResultsDelegate(ByVal searchTerm As String, _

                                                      ByVal searchType As SearchType) _

                                                      As Integer

 

 

 

   Private Delegate Function GetResultsDelegate(ByVal searchTerm As String, _

                                                ByVal searchType As SearchType, _

                                                ByVal searchQty As Integer) _

                                                As List(Of SearchResult)

 

   

End Class