Imports Microsoft.AnalysisServices.AdomdClient
Imports System.Data

Partial Class _Default
    Inherits System.Web.UI.Page

    Private ReadOnly Property mWarenkorb() As ArrayList
        Get 'Warenkorb persistenz
            If IsNothing(ViewState("warenkorb")) Then
                ViewState("warenkorb") = New ArrayList()
            End If
            Return DirectCast(ViewState("warenkorb"), ArrayList)
        End Get
    End Property


    Protected Sub cmdKaufen_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdKaufen.Click

        'Produkt hinzufügen
        mWarenkorb.Add(ddlProdukt.SelectedValue)
        dgWarenkorb.DataSource = mWarenkorb
        dgWarenkorb.DataBind()

        'Empfehlungen suchen
        Dim lEmpfehlung As DataTable = GetEmpfehlung(mWarenkorb)

        dgEmpfehlung.DataSource = lEmpfehlung
        dgEmpfehlung.DataBind()
    End Sub


    Private Function GetEmpfehlung(ByVal aWarenkorb As ArrayList) As DataTable
        'Abfrage zusammenstellen
        ' SELECT FLATTENED
        '    Predict([Products],4) as [Products]
        ' FROM
        '    [WebSale]
        ' NATURAL PREDICTION JOIN
        ' (SELECT (SELECT 'PRODUCT1' as Product
        '   UNION SELECT 'PRODUCT2' as Product) as Products) as t

        Dim lSQL As String = "SELECT FLATTENED " & vbCrLf & _
                                  "Predict([Products],4) as [Products] " & vbCrLf & _
                             "FROM" & vbCrLf & _
                                 "[WebSale] " & vbCrLf & _
                             "NATURAL PREDICTION JOIN " & vbCrLf & _
                             "(SELECT ( "
        Dim lFirst As Boolean = True
        For Each iProdukt As String In aWarenkorb
            If lFirst Then
                lFirst = False
            Else
                lSQL += " UNION "
            End If
            lSQL += "SELECT '" & iProdukt & "' AS [Product]" & vbCrLf
        Next
        lSQL += ") AS [Products] ) as t"

        'Empfehlung abfragen
        Dim lCommand As New AdomdCommand(lSQL, _
                           New AdomdConnection("Data Source=localhost; Catalog=webSaleDB"))
        Dim lDataTable As New DataTable
        Dim lDataAdapter As New AdomdDataAdapter(lCommand)
        lDataAdapter.Fill(lDataTable)
        Return lDataTable
    End Function

End Class
