Imports <xmlns:mms="http://schemas.microsoft.com/LiveSearch/2008/04/XML/multimedia">
Imports <xmlns:s="http://schemas.microsoft.com/LiveSearch/2008/04/XML/element">
Imports System.IO
Imports System.Xml.Linq


Partial Public Class Page
    Inherits UserControl

    Private Delegate Sub UpdateListDelegate(ByVal images As List(Of Image))

    Private Const SEARCH_URL = "http://api.search.live.net/xml.aspx?AppId={0}&Market={1}&Query={2}&Sources=image"
    Private Const APP_ID = ""


    Public Sub New()
        InitializeComponent()
    End Sub

    Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim url As String = String.Format(SEARCH_URL, _
                                         APP_ID, _
                                         "cs-CZ", _
                                         Uri.EscapeUriString(txtSearch.Text))

        Dim request As WebRequest = WebRequest.Create(New Uri(url))

        request.BeginGetResponse(AddressOf OnData, request)
    End Sub

    Private Sub OnData(ByVal e As IAsyncResult)
        Dim request As WebRequest = CType(e.AsyncState, WebRequest)
        Dim response As WebResponse = CType(request.EndGetResponse(e), WebResponse)

        Dim data As StreamReader = New StreamReader(response.GetResponseStream())
        Dim d As XDocument = XDocument.Parse(data.ReadToEnd())

        Dim images As List(Of Image) = (From i In d...<mms:ImageResult> _
                     Select New Image() _
                            With _
                            { _
                                .Url = i.<mms:Thumbnail>.<mms:Url>.Value, _
                                .Title = i.<mms:Title>.Value _
                            }).ToList()



        lstData.Dispatcher.BeginInvoke(New UpdateListDelegate(AddressOf UpdateUI), images)
    End Sub

    Private Sub UpdateUI(ByVal images As List(Of Image))
        lstData.ItemsSource = images
    End Sub
End Class