Musiklänkar, script till MediaMonkey..

8 posts / 0 new
Last post
benzzon
benzzon's picture
Musiklänkar, script till MediaMonkey..
 
Webradio, Sundsvall Guld 106,6: http://www.guld.nu/webbspelare.htm
 
Spotify playlists:
 
 
 
 

http://quadzilla.no-ip.info:8000

Blues: http://1.fm/Stations/Blues/TuneIn.aspx
http://www.mymusicstream.com/music/blues.php

temp: http://radio.myth.se:8000/listen.pls

*** Sök artist/band och hitta liknande musik..
LastFM: http://www.last.fm/
 
*** Sök musik-kategori och BPM:
 

CUE Splitter (Flac): http://www.enfis.it/downloads.php?cat_id=1
Media Player Flac plug-in: http://www.illiminable.com/ogg/
Winamp Flac plug-in: http://flac.sourceforge.net/download.html (Flac 1.1.2)

*** Tips for managing mp3's: 
 
*** MixMeister BPM Analyzer: Writes BPM to Mp3-tag (BPM).
 
Spotify playlists:
 
Invites:
 
 
benzzon
benzzon's picture
.
benzzon
benzzon's picture
.
benzzon
benzzon's picture
.

    ' *** MediaMonkey,CTRL-Arrowkeys. ("ctrl-keys.vbs")
    ' *** Fast forward,backward & volume up,down.
    ' *** 080112: Created script based on others..
    '
    ' Installation:
    ' - just copy this code to a new text file,name it 'something.vbs'
    '   and save into your 'MediaMonkey\Scripts\Auto'-Folder
    '

Option Explicit

    Sub OnStartup()
        '
        Dim MenuItemFolder,MenuItemBackward,MenuItemForward,MenuItemVolumeUp,MenuItemVolumeDown
        '
        Set MenuItemFolder = SDB.UI.AddMenuItemSub(SDB.UI.Menu_Scripts,1,1)
        MenuItemFolder.Caption = "CTRL-Arrows"
        '
        Set MenuItemBackward = SDB.UI.AddMenuItem(MenuItemFolder,2,1)
        MenuItemBackward.Caption = "Backward"
        MenuItemBackward.ShortCut = "Ctrl+Left"
        MenuItemBackward.UseScript = Script.ScriptPath
        MenuItemBackward.OnClickFunc = "Backward"
        '
        Set MenuItemForward = SDB.UI.AddMenuItem(MenuItemFolder,2,2)
        MenuItemForward.Caption = "Forward"
        MenuItemForward.ShortCut = "Ctrl+Right"
        MenuItemForward.UseScript = Script.ScriptPath
        MenuItemForward.OnClickFunc = "Forward"
        '

        Set MenuItemVolumeUp = SDB.UI.AddMenuItem(MenuItemFolder,2,3)
        MenuItemVolumeUp.Caption = "Volume Up"
        MenuItemVolumeUp.ShortCut = "Ctrl+Up"
        MenuItemVolumeUp.UseScript = Script.ScriptPath
        MenuItemVolumeUp.OnClickFunc = "VolumeUp"
        '

        Set MenuItemVolumeDown = SDB.UI.AddMenuItem(MenuItemFolder,2,3)
        MenuItemVolumeDown.Caption = "Volume Down"
        MenuItemVolumeDown.ShortCut = "Ctrl+Down"
        MenuItemVolumeDown.UseScript = Script.ScriptPath
        MenuItemVolumeDown.OnClickFunc = "VolumeDown"
        '

    End Sub

    Sub Backward(ByVal MenuItemBackward)
        '
        If SDB.Player.IsPlaying = True Then
            SDB.Player.PlayBackTime = SDB.Player.PlayBackTime - 5000
        End If
        '
    End Sub

    Sub Forward(ByVal MenuItemForward)
        '
        If SDB.Player.IsPlaying = True Then
            SDB.Player.PlayBackTime = SDB.Player.PlayBackTime + 5000
        End If
        '
    End Sub

    Sub VolumeUp(ByVal MenuItemVolumeUp)
        '
        If SDB.Player.IsPlaying = True Then
            SDB.Player.Volume = SDB.Player.Volume + 0.1
        End If
        '
    End Sub

    Sub VolumeDown(ByVal MenuItemVolumeDown)
        '
        If SDB.Player.IsPlaying = True Then
            SDB.Player.Volume = SDB.Player.Volume - 0.1
        End If
        '
    End Sub

 
benzzon
benzzon's picture
.
' *** Move Device Content.. ("move-device.vbs")

' Put this script in MediaMonkey folder "Scripts\Auto".
' -> Make sure every Device (harddrive) has a Label (Library -> Location)
' -> Select Tools -> Scripts -> Move Device Content


Option Explicit

    Sub OnStartup()
        Dim mnuChange_HDD_Serial, MenuItemFolder

        Set MenuItemFolder = SDB.UI.AddMenuItemSub(SDB.UI.Menu_Scripts,1,1)
        MenuItemFolder.Caption = "Move Device Content"

        Set mnuChange_HDD_Serial = SDB.UI.AddMenuItem(MenuItemFolder,2,1)
        mnuChange_HDD_Serial.Caption = "Show device-dialog"
        mnuChange_HDD_Serial.ShortCut = "Ctrl+m"
        mnuChange_HDD_Serial.UseScript = Script.ScriptPath
        mnuChange_HDD_Serial.OnClickFunc = "Change_HDD_Serial"

    End Sub


Sub Change_HDD_Serial(ByVal mnuChange_HDD_Serial)
  Const PanelWidth = 200
  Const PanelHeight = 100
  Const objSpace = 10
 
  Dim cntMedias
  Dim arrRadioMedia()
  Dim arrRadioMediaID()
  Dim cntDrives
  Dim arrRadioDrive()
  Dim arrRadioDriveLetter()
  Dim arrRadioDriveSN()
  Dim arrRadioDriveTypes()

  Dim SDB
  Set SDB = CreateObject("SongsDB.SDBApplication")
  Dim FSO
  Set FSO = CreateObject("Scripting.FileSystemObject")
  Dim UI
  Set UI = SDB.UI

  'Create the window to be shown
  Dim Form
  Set Form = UI.NewForm
  Form.Common.ClientWidth = objSpace + PanelWidth + objSpace + PanelWidth + objSpace
  Form.FormPosition = 4   ' Screen Center
  Form.BorderStyle = 3    ' Dialog
  Form.Caption = "Move MediaMonkey's Device Content"
 
  Dim Label
  Set Label = UI.NewLabel(Form)
  Label.Caption = "from ..."
  Label.Common.Top = objSpace
  Label.Common.Left = objSpace
  Label.Common.Width = PanelWidth
 
  Set Label = UI.NewLabel(Form)
  Label.Caption = "to ..."
  Label.Common.Top = objSpace
  Label.Common.Left = objSpace + PanelWidth + objSpace
  Label.Common.Width = PanelWidth
 
  Dim PanelMedia
  Set PanelMedia = UI.NewPanel(Form)
  PanelMedia.Common.SetRect objSpace, objSpace + Label.Common.Height + objSpace, PanelWidth, PanelHeight
 
  'Add Medias
  Dim ds
  Dim RadioBtn
  Dim BtnTop
  Dim Caption
 
  BtnTop = 0
  cntMedias = 0
  Set ds = SDB.DataBase.OpenSQL("SELECT * FROM Medias WHERE DriveType < 10")
  While Not ds.EOF
    Caption = ""
    'If ds.StringByName("Driveletter") <> "" Then Caption = Chr(ds.ValueByName("DriveLetter") + 65) & ": "
    If ds.StringByName("Label") <> "" Then
      'If Caption <> "" Then Caption = Caption & "- "
      Caption = Caption & ds.StringByName("Label")
    End If
    If ds.StringByName("ShowLabel") <> "" Then
      If Caption <> "" Then Caption = Caption & "- "
      Caption = Caption & ds.StringByName("ShowLabel")
    End If
    If Caption = "" Then Caption = ds.StringByName("Comment")
   
    Set RadioBtn = UI.NewRadioButton(PanelMedia)
    RadioBtn.Common.Top = BtnTop
    RadioBtn.Common.Width = PanelWidth
    BtnTop = BtnTop + RadioBtn.Common.Height + 3
    PanelMedia.Common.ClientHeight = BtnTop
    RadioBtn.Caption = Caption
    RadioBtn.Common.Hint = ds.StringByName("Comment")
   
    cntMedias = cntMedias + 1
    ReDim Preserve arrRadioMedia(cntMedias)
    ReDim Preserve arrRadioMediaID(cntMedias)
    Set arrRadioMedia(cntMedias) = RadioBtn
    arrRadioMediaID(cntMedias) = ds.ValueByName("IDMedia")
   
    ds.Next
  Wend
 
  Dim PanelDrives
  Set PanelDrives = UI.NewPanel(Form)
  PanelDrives.Common.SetRect objSpace + PanelWidth + objSpace, objSpace + Label.Common.Height + objSpace, PanelWidth, PanelHeight
 
  'Add DriveLetters
  BtnTop = 0
  cntDrives = 0
  Dim Drive
  For Each Drive In FSO.Drives
    If Drive.IsReady Then
      Caption = Drive.DriveLetter & ":"
      Caption = Caption & " - " & Drive.VolumeName
   
      Set RadioBtn = UI.NewRadioButton(PanelDrives)
      RadioBtn.Common.Top = BtnTop
      RadioBtn.Common.Width = PanelWidth
      BtnTop = BtnTop + RadioBtn.Common.Height + 3
      PanelDrives.Common.ClientHeight = BtnTop
      RadioBtn.Caption = Caption
     RadioBtn.Common.Hint = CStr(Drive.SerialNumber) 'TotalSize / 1024 / 1024 / 1024
   
      cntDrives = cntDrives + 1
      ReDim Preserve arrRadioDrive(cntDrives)
      ReDim Preserve arrRadioDriveLetter(cntDrives)
      ReDim Preserve arrRadioDriveSN(cntDrives)
      ReDim Preserve arrRadioDriveTypes(cntDrives)
      Set arrRadioDrive(cntDrives) = RadioBtn
      arrRadioDriveLetter(cntDrives) = Drive.SerialNumber
      arrRadioDriveSN(cntDrives) = Drive.SerialNumber
      arrRadioDriveTypes(cntDrives) = Drive.DriveType + 1
    End If
  Next
 
  If PanelDrives.Common.Height > PanelMedia.Common.Height Then
    BtnTop = PanelDrives.Common.Height
  Else
    BtnTop = PanelMedia.Common.Height
  End If
 
  Set Label = UI.NewLabel(Form)
  Label.Caption = "Only the Database-Entries are updates. The Files aren't moved physically on the Harddisk!"
  Label.Common.Top = objSpace + Label.Common.Height + objSpace + BtnTop + objSpace
  Label.Common.Left = objSpace
  Label.Common.Height = Label.Common.Height * 2
  Label.Common.Width = Form.Common.ClientWidth - objSpace - objSpace
  Label.MultiLine = True
 
  Dim Btn
  Set Btn = UI.NewButton(Form)
 
  BtnTop = Label.Common.Top + Label.Common.Height + objSpace
 
  Btn.Caption = SDB.Localize("&Ok")
  Btn.Common.SetRect objSpace, BtnTop, PanelWidth, 25
  Btn.ModalResult = 1
  Btn.Default = True

  Set Btn = UI.NewButton(Form)
  Btn.Caption = SDB.Localize("&Cancel")
  Btn.Common.SetRect objSpace + PanelWidth + objSpace, BtnTop, PanelWidth, 25
  Btn.ModalResult = 2
  Btn.Cancel = True
 
  Form.Common.ClientHeight = BtnTop + 25 + objSpace
 
  If Form.ShowModal = 1 Then 'OK
    Dim SelMedia     'Media-ID
    Dim SelDrive     'Drive Letter
    Dim selDriveSN   'SerialNumber
    Dim SelDriveType 'Drive Type
    SelMedia = ""
    SelDrive = ""
   
    Dim intTemp
    For intTemp = 1 To cntMedias
      If arrRadioMedia(intTemp).Checked Then SelMedia = arrRadioMediaID(intTemp)
    Next
    For intTemp = 1 To cntDrives
      If arrRadioDrive(intTemp).Checked Then
        SelDrive = arrRadioDriveLetter(intTemp)
        selDriveSN = arrRadioDriveSN(intTemp)
        SelDriveType = arrRadioDriveTypes(intTemp)
      End If
    Next
   
    If (SelDrive <> "") And (SelMedia <> "") Then
      If SDB.MessageBox("Are you really sure?", 0, Array(0, 2)) = 6 Then
        Set ds = SDB.DataBase.OpenSQL("SELECT * FROM Medias WHERE SerialNumber = " & selDriveSN)
        If Not ds.EOF Then
          SDB.DataBase.ExecSQL ("Update Songs set IDMedia = " & ds.StringByName("IDMedia") & " WHERE IDMedia = " & SelMedia)
        Else
          SDB.DataBase.ExecSQL ("Update Medias set SerialNumber = " & selDriveSN & ", DriveType = " & SelDriveType & " WHERE IDMedia = " & SelMedia)
        End If
      SDB.MessageBox "Please restart MediaMonkey", 2, Array(4)
      End If
    End If
  End If
End Sub

benzzon
benzzon's picture
.

' *** Copy selected files.. ("copy-files.vbs")
' 081227 nbn: Added folder selection, and file-prefix option.

Option Explicit
Dim fso : Set fso = CreateObject("Scripting.FileSystemObject")
Dim CopyOver : CopyOver = True

Sub onStartUp

   Dim CMIArray
   CMIArray = Array(SDB.UI.Menu_Pop_TrackList, SDB.UI.Menu_Pop_NP, SDB.UI.Menu_Pop_Tree)
   
   Dim i, MI
   For i = 0 To UBound(CMIArray)
     SDB.UI.AddMenuItemSep CMIArray(i), 0, 0
   
     Set MI = SDB.UI.AddMenuItem(CMIArray(i), 0, 0)
     MI.Caption = "Copy selected files.."
     MI.OnClickFunc = "RunCopy"
     MI.UseScript = Script.ScriptPath
     MI.IconIndex = 1
   Next

End Sub

Function RunCopy(arg)

  Dim WShell, Result, Command

'  Command = """copy """ & SDB.SelectedSongList.Item(0).Path & "" & " c:\mp3_temp" & chr(34)
'  Command = "copy " & chr(34) & SDB.SelectedSongList.Item(0).Path & chr(34) & " " & chr(34) & "d:\mp3_temp" & chr(34)

'  Set WShell = CreateObject("WScript.Shell")
'  Result = WShell.Run(Command, 1, 0)
' msgbox(Command)

 Dim strFolderPath
 strFolderPath = InputBox("Enter path to copy mp3-files to...","*** Step 1", "c:\mp3_temp\")

 Dim intFileNr
 intFileNr = InputBox("Enter 3 digit start-nr for optional filename-prefix (to preserve play order)." & vbCrLf & "Enter blank to keep original filename.","*** Step 2", "000")

 Dim i
 Dim list : Set list = SDB.SelectedSongList 
 dim strCopyTo

 For i = 0 To list.Count-1
    if intFileNr <> "" then
        strCopyTo = strFolderPath & right("000" & intFileNr,3) & "_" & GetFileName(SDB.SelectedSongList.Item(i).Path)
        intFileNr=intFileNr + 1
    else
        strCopyTo = strFolderPath
    end if
    Call fso.CopyFile(SDB.SelectedSongList.Item(i).Path,strCopyTo,CopyOver)
 Next


End Function

Function GetFileName(flname)
   
    Dim posn, i
    Dim fName
   
    posn = 0
    'find the position of the last "\" character in filename
    For i = 1 To Len(flname)
        If (Mid(flname, i, 1) = "\") Then posn = i
    Next

    'get filename without path
    fName = Right(flname, Len(flname) - posn)

    GetFileName = fName
End Function

benzzon
benzzon's picture
.

' *** Export playlists.. ("export-playlists.vbs")

 

Option Explicit

 

Dim path

Dim fso

Dim FSO2

 

' Recursively process all playlists

Sub GetPlaylists(Playlists, Plst, Prefix)

    If Prefix <> "" Then Prefix = Prefix & "\"

   

    Dim SubPlsts : Set SubPlsts = Plst.ChildPlaylists

 

    Dim i, SubPlst, Title

    For i = 0 To SubPlsts.Count - 1

        Set SubPlst = SubPlsts.Item(i)

        Title = Prefix & SubPlst.Title

        If Not Playlists.Exists(Title) Then

            Playlists.Add Title, SubPlst

        End If

        GetPlaylists Playlists, SubPlst, Title

    Next

End Sub

 

 

Sub ExportM3Us

    Dim iniF : Set iniF = SDB.IniFile

    path = SDB.SelectFolder(iniF.StringValue("Scripts", "LastExportM3UsDir"), SDB.Localize("Select where to export all M3U files."))

    If path = "" Then Exit Sub

    If Right(path, 1) <> "\" Then path = path & "\"

    iniF.StringValue( "Scripts", "LastExportM3UsDir") = path

    Set iniF = Nothing

   

    ' Connect to the FileSystemObject

    Set fso = SDB.Tools.FileSystem

    Set FSO2 = CreateObject("Scripting.FileSystemObject")

   

    Dim Playlists : Set Playlists = CreateObject("Scripting.Dictionary")

 

    ' Prepare a list of all playlists

    GetPlaylists Playlists, SDB.PlaylistByTitle(""), ""

   

    ' Go through the list and export each playlist

    Dim i, plst, plsts, titles, title, tracks, folder

    plsts = playlists.Items

    titles = playlists.Keys

 

    For i = 0 To playlists.Count - 1

        Set plst = plsts(i)

        Set tracks = plst.Tracks

        title = Titles(i)

       

        folder = ""

        If Instr(1, title, "\", 1) > 0 Then

            folder = Left(title, InstrRev(title, "\", -1, 1))

            title = Mid(title, InstrRev(title, "\", -1, 1) + 1)

            If Not FSO2.FolderExists(path & folder) Then

                FSO2.CreateFolder path & folder

            End If

        End If

       

        If tracks.Count>0 Then

            Call CreateM3UFile(path & folder & fso.CorrectFilename(title) & ".m3u", tracks)

        End If

    Next

   

    SDB.MessageBox "Exporting playlists complete.", mtInformation, Array(mbOK)

End Sub

 

 

Sub CreateM3UFile(M3UPath, Tracks)

    Dim fOut : Set fOut = fso.CreateTextFile(M3UPath, True)

    fOut.WriteLine "#EXTM3U"

   

    Dim i, Track, tLen, tArt, tTit

    For i = 0 To Tracks.Count - 1

        Set Track = Tracks.Item(i)

       

        tLen = Track.SongLength

        tArt = Track.ArtistName

        tTit = Track.Title

       

        fOut.WriteLine("#EXTINF:" _

                & IIf(tLen>0, tLen \ 1000, "-1") & "," _

                & IIf(tArt<>"", IIf(tTit<>"", tArt & " - " & tTit, tArt), tTit) _

                )

        fOut.WriteLine Track.Path

    Next

    fOut.Close

End Sub

 

 

Function IIf(Test, rTrue, rFalse)

    If Test Then IIf = rTrue Else IIf = rFalse

End Function

 

 

benzzon
benzzon's picture
sql-viewer (bzn4).vbs

' From http://www.mediamonkey.com/forum/viewtopic.php?t=24841%20
' MediaMonkey Script
'
' NAME: SQL Viewer
' VERSION: 2.4
' LAST UPDATED: 2009-10-25
' AUTHOR: Bex
' DATE : 2007-01-13

' 120709 benzzon: Added function OnStartup() for easier use with portable MM.
'/////////////////////////////////////////////////////////////////////////////////////////////////'
Option Explicit


    Sub OnStartup()
        Dim mnuSQLViewer, MenuItemFolder

        Set MenuItemFolder = SDB.UI.AddMenuItemSub(SDB.UI.Menu_Scripts,1,1)
        MenuItemFolder.Caption = "SQL-Viewer (bzn4)"

        Set mnuSQLViewer = SDB.UI.AddMenuItem(MenuItemFolder,2,1)
        mnuSQLViewer.Caption = "Show SQLViewer-dialog"
        mnuSQLViewer.ShortCut = "Ctrl+F9"
        mnuSQLViewer.UseScript = Script.ScriptPath
        mnuSQLViewer.OnClickFunc = "SqlViewer"

    End Sub

 
Const akLeft = 1
Const akTop = 2
Const akRight = 4
Const akBottom = 8
Const alTop = 1
Const alBottom = 2
Const alClient = 5
Const mmListDropdown = 2
Const mmFormScreenCenter = 4
Public styleOn

Dim Tables(),Fields(),History(),Saves(),Templates(),Functions(),SongData()

Dim INI : Set INI = SDB.IniFile
Dim UI  : Set UI  = SDB.UI
Dim DB  : Set DB  = SDB.DataBase

' benzzon // Sub SqlViewer() 
Sub SqlViewer(ByVal mnuSQLViewer) 

  Dim Form,Foot,Top1,Top2,Top3,Mle,WB,HTML,Spi
  Dim DlgWidth,LastRun,LastRows,LastTime,LastHtml,LastSql

  DB.ExecSQL("CREATE TABLE If NOT EXISTS TmpSqlHist (tmpIDnr INTEGER PRIMARY KEY, tmpRows INTEGER, tmpTime TEXT, tmpHtml TEXT, tmpSql TEXT)")
  DB.ExecSQL("CREATE TABLE If NOT EXISTS TmpSqlSaves (tmpIDnr INTEGER PRIMARY KEY, tmpName TEXT, tmpRows INTEGER, tmpTime TEXT, tmpHtml TEXT, tmpSql TEXT)")
  DlgWidth = 700

  ' Create the window to be shown
  Set Form = UI.NewForm
  Form.Common.SetRect 50, 50, DlgWidth, 400
  Form.Common.MinWidth = 720
  Form.Common.MinHeight = 410
  Form.FormPosition = mmFormScreenCenter
  Form.Caption = "SQL Query Viewer & DDL/DML Executor (SQLite: " & DB.OpenSQL("SELECT SQLITE_VERSION(*)").ValueByIndex(0) &")"
  Form.BorderStyle = 2
  Form.StayOnTop = True

  'Create the third panel from the Top of the window for hosting window action buttons
  Set Top3 = UI.NewTranspPanel(Form)
  Top3.Common.Align = alTop
  Top3.Common.Height = 28

  'Create the second panel from the Top of the window to host the sql-input window
  Set Top2 = UI.NewTranspPanel(Form)
  Top2.Common.Align = alTop
  Top2.Common.Height = 155

  'Create the first panel from the Top hosting various buttons
  Set Top1 = UI.NewTranspPanel(Form)
  Top1.Common.Align = alTop
  Top1.Common.Height = 102
 
  'Create a Footer
  Set Foot = UI.NewTranspPanel(Form)
  Foot.Common.Align = alBottom
  Foot.Common.Height = 28
  Foot.Common.ControlName = "Foot"
 
  ' Create a web browser component
  Set WB = UI.NewActiveX(Form, "Shell.Explorer")
  WB.Common.Align = alClient      ' Fill all client rectangle
  WB.Common.ControlName = "WB"

  Set SDB.Objects("holdHTML") = CreateObject("Scripting.Dictionary")
  SDB.Objects("holdHTML").RemoveAll
  SDB.Objects("holdHTML").add 0,""

  Call CreateDrd(Top1,  2,  2,700,20,"History",1+2+4,0,"History",History,"AddFromHist","Select a History record to add it to the SQL Window")
  Call CreateDrd(Top1,  2, 27,560,20,"Saves","",0,"Saves",Saves,"AddFromSave","Select a Saved record to add it to the SQL Window")
  Dim SavesItemIdx : SavesItemIdx=Form.Common.TopParent.Common.ChildControl("Saves").ItemIndex
  Call CreateBtn(Top1,564, 25, 40,24,"Save","SaveBtn","SavCurSql","","Save Current Query/Statement To Selected Name","","",Eval(SavesItemIdx>0))
  Call CreateBtn(Top1,605, 25, 48,24," Save as","","Saveas","","Save Current Query/Statement to a New Name","","",True)
  Call CreateBtn(Top1,655, 25, 48,24,"Delete","DelBtn","DelSave","","Delete selected Save","","",Eval(SavesItemIdx>0))
 
  Call CreateBtn(Top1,  1, 50, 50,23,"SELECT"  ,"","AddSQLtxt", "","","","",True)
  Call CreateBtn(Top1, 51, 50, 20,23," *"      ,"","AddSQLtxt", "","","","",True)
  Call CreateBtn(Top1, 72, 50, 60,23,"COUNT(*)","","AddSQLtxt", "","","","",True)
  Call CreateBtn(Top1,133, 50, 50,23,"FROM"    ,"","AddSQLtxt", "","","","",True)
  Call CreateBtn(Top1,184, 50, 50,23,"WHERE"   ,"","AddSQLtxt", "","","","",True)
  Call CreateBtn(Top1,235, 50, 60,23,"GROUP BY","","AddSQLtxt", "","","","",True)
  Call CreateBtn(Top1,296, 50, 55,23,"HAVING"  ,"","AddSQLtxt", "","","","",True)
  Call CreateBtn(Top1,352, 50, 60,23,"ORDER BY","","AddSQLtxt", "","","","",True)
  Call CreateBtn(Top1,413, 50, 50,23,"Comma"   ,"","AddSQLtxt", "","","","",True)
  Call CreateBtn(Top1,464, 50, 20,23," ="      ,"","AddSQLtxt", "","","","",True)
 
  Call CreateBtn(Top1,504, 50, 55,23,"RemVBS","","RemVBS","","Removes Surrounding Spaces, Double quotes, Ampersand and Underscore","","",True)
  Call CreateBtn(Top1,560, 50, 55,23,"AddVBS","","AddVBS","","The Opposite of RemVBS with specified Indent Spaces","","",True)
  Call CreateLbl(Top1,620, 55, 20,25,"Indent:","")
  Set Spi = UI.NewSpinEdit(Top1)
  Spi.Common.SetRect       662, 51, 40,20
  Spi.Common.ControlName = "IndSpaces"
  Spi.MinValue = 0
  Spi.MaxValue = 40
  Spi.Common.Hint = "Indent Spaces in AddVBS"
  Spi.Value = INI.IntValue("SqlViewer","IndSpaces")
  Script.RegisterEvent Spi, "OnChange", "ChangeIndSpaces"
 
  Call CreateDrd(Top1,  2, 76,150,20,"Tables","",0,"Tables",Tables,"PopuFields","Select a Table and Press Add to add it to the SQL Window")
  Call CreateBtn(Top1,156, 74, 40,24,"&Add","","AddTable","","Adds Selected Table to the SQL Window","","",True)
  Call CreateDrd(Top1,200, 76,200,20,"Fields","",0,"Fields",Fields,"AddField","Select a Field to add it to the SQL Window")
  Call CreateCbx(Top1,404, 78,200,20,"Add as Table.Field","IfTable","If Checked:"& VbNewline &"Fields are Added with its TableName"&_
                                          VbNewline &"If not Checked:"& VbNewline &"Only FieldName is added",INI.BoolValue("SqlViewer","AddTable"),"OnClickAddTable")
  Call CreateDrd(Top1,520, 76,182,20,"SongData","",0,"SongData",SongData,"AddSongData","Select a Field to add its data from the Selected song to the SQL Window")
  'Call CreateDrd(Top1,520, 51,100,20,"Functions",0,"Functions",Functions,"AddFunction","Select a Function to add it to the SQL Window")

  ' Create a button that runs the SQL
  Call CreateLbl(Top3,135,  7, 70, 25,"Display Only","")
  Call CreateLbl(Top3,265,  7, 70, 25,"Rows","")
  Set Spi = UI.NewSpinEdit(Top3)
  Spi.Common.SetRect       200,  4, 60, 20
  Spi.Common.ControlName = "MaxRows"
  Spi.MinValue = 1
  Spi.MaxValue = 9999
  Spi.Value = INI.IntValue("SqlViewer","MaxRows")
  Script.RegisterEvent Spi, "OnChange", "ChangeMaxRows"
  Call CreateBtn(Top3,  2,  2, 120, 24,"&Run Select Query","","RunQuery","","","","",True)
  Call CreateBtn(Top3,300,  2, 180, 24,"&Execute DDL/DML Statement","","ExecSql","","","","",True)

  Call CreateLbl(Foot,  5,  2,70,20,"Rows:","")
  Call CreateLbl(Foot, 40,  2,70,20,0,"Rows")
  Call CreateLbl(Foot,  9, 17,70,20,"Time:","")
  Call CreateLbl(Foot, 40, 17,70,20,Trim(" "),"eTime") 'If I write "" then the controlname eTime is Displayed in the Foot????
  Call CreateBtn(Foot,592,  5,85,24,"&Close","","OnClose", akRight,"","","Cancel",True)
  Call CreateBtn(Foot,500,  5,85,24,"Clear All","","ClearAll", akRight,"","","",True)

  'Create sql-input window
  Set Mle = UI.NewMultiLineEdit(Top2)
  Mle.Common.Align = alClient
  Mle.Common.ControlName = "sql"
  Mle.Text = Trim(" ") 'If I write "" then the controlname is written as text????

  Form.SavePositionName = "SQLWindow"
  Form.Common.Visible = True
  SDB.Objects("SQLThingy") = Form  ' Save reference to the form somewhere, otherwise it would simply disappear
End Sub

Sub ClearAll(Btn)
  Dim Top : Set Top=Btn.Common.TopParent.Common
  Top.ChildControl("History").ItemIndex=0
  Top.ChildControl("Saves").ItemIndex=0
  Top.ChildControl("Tables").ItemIndex=0
  Top.ChildControl("Fields").ItemIndex=0
  Top.ChildControl("SongData").ItemIndex=0
  Top.ChildControl("sql").Text=""
  Top.ChildControl("WB").SetHTMLDocument("")
  SDB.Objects("holdHTML").RemoveAll
  SDB.Objects("holdHTML").add 0,""
  Top.ChildControl("Rows").Caption=""
  Top.ChildControl("eTime").Caption=""
End sub

Sub SavCurSql(Btn)
  Dim Top,Name,rows,etime,html,sql
  Set Top=Btn.Common.TopParent.Common
  If Trim(Top.ChildControl("sql").Text) = "" Then Exit Sub
  Name  = FixSQL(Top.ChildControl("Saves").Text)
  rows  = Top.ChildControl("Rows").Caption
  If Trim(rows) = "" Then rows = "Null"
  etime = FixSQL(Top.ChildControl("etime").Caption)
  html  = FixSQL(SDB.Objects("holdHTML").item(0))
  sql   = FixSQL(Top.ChildControl("sql").Text)
  DB.ExecSQL("UPDATE TmpSqlSaves SET tmpRows="& rows &", tmpTime="& etime &", tmpHtml="& html &", tmpSql="& sql &" WHERE tmpIDnr||' '||tmpName="& Name)
End sub

Sub Saveas(inBtn)
  Dim Form,result,Btn,i,Edt,SavesDD,Name,rows,etime,html,sql
  If Trim(inBtn.Common.TopParent.Common.ChildControl("sql").Text) = "" Then Exit Sub

  Set Form = SDB.UI.NewForm
  Form.Common.SetRect 0, 0, 250,130
  Form.FormPosition = 4   ' Screen Center
  Form.BorderStyle = 3    ' Dialog
  Form.Caption = "Name Your Save"
 
  Call CreateLbl(Form, 20, 20,70,20,"Give It a Name:","")
  Set Edt = UI.NewEdit(Form)
  Edt.Common.SetRect  20, 40,200,20
  Edt.Common.ControlName = "SaveName"

  Call CreateBtn(Form, 30,80,85,25,SDB.Localize("&Save"),"","","","",1,"Default",True)
  Call CreateBtn(Form,130,80,85,25,SDB.Localize("&Cancel"),"","","","",2,"Cancel",True)
 
  result = Form.ShowModal
  If result = 1 Then
     Set SavesDD = inBtn.Common.TopParent.Common.ChildControl("Saves")
     Name  = FixSQL(Form.Common.ChildControl("SaveName").Text)
     rows  = inBtn.Common.TopParent.Common.ChildControl("Rows").Caption
     if Trim(rows) = "" Then rows = "Null"
     etime = FixSQL(inBtn.Common.TopParent.Common.ChildControl("etime").Caption)
     html  = FixSQL(SDB.Objects("holdHTML").item(0))
     sql   = FixSQL(inBtn.Common.TopParent.Common.ChildControl("sql").Text)
     DB.ExecSQL("INSERT INTO TmpSqlSaves (tmpName, tmpRows, tmpTime, tmpHtml, tmpSql) "&_
                "SELECT "& Name &", "& rows &", "& etime &", "& html &", "& sql)
     Call ClearDropDown(SavesDD)
     Call CreateDropDownItems("Saves")
     Call FillDropDownFromArray(SavesDD, Saves)
     SavesDD.ItemIndex=1
  Else
     Exit Sub
  End If
End sub

Sub DelSave(Btn)
   Dim SavesDD
   Set SavesDD = Btn.Common.TopParent.Common.ChildControl("Saves")
   If SavesDD.ItemIndex = 0 Then Exit Sub
   DB.ExecSQL("DELETE FROM TmpSqlSaves WHERE tmpIDnr||' '||tmpName="& FixSQL(SavesDD.Text))
   SavesDD.DeleteItem(SavesDD.ItemIndex)
   SavesDD.ItemIndex = 0
   Btn.Common.TopParent.Common.ChildControl("sql").Text      = ""
   Btn.Common.TopParent.Common.ChildControl("WB").SetHTMLDocument("")
   SDB.Objects("holdHTML").RemoveAll
   SDB.Objects("holdHTML").add 0,""
   Btn.Common.TopParent.Common.ChildControl("Rows").Caption  = ""
   Btn.Common.TopParent.Common.ChildControl("eTime").Caption = ""
End Sub

Sub ChangeIndSpaces(Spi)
  INI.IntValue("SqlViewer","IndSpaces")=Spi.Value
End Sub

Sub ChangeMaxRows(Spi)
  INI.IntValue("SqlViewer","MaxRows")=Spi.Value
End Sub

Sub OnClickAddTable(Cbx)
  INI.BoolValue("SqlViewer","AddTable")=Cbx.Checked
End Sub

Sub ExecSql(Pnl)
   Dim t(1),etime,sql,HistDD
   Pnl.Common.TopParent.Common.ChildControl("Rows").Caption  = ""
   Pnl.Common.TopParent.Common.ChildControl("eTime").Caption = ""
   Pnl.Common.TopParent.Common.ChildControl("WB").SetHTMLDocument("")
   SDB.Objects("holdHTML").RemoveAll
   SDB.Objects("holdHTML").add 0,""
   sql = Pnl.Common.TopParent.Common.ChildControl("sql").Text
   If sql="" Then Exit Sub
   Set HistDD = Pnl.Common.TopParent.Common.ChildControl("History")
   t(0) = Timer()
   DB.ExecSQL(sql)
   t(1) = Timer()
   etime = FormatNumber(Round(t(1)-t(0),3),3) & " sec"
   DB.ExecSQL("INSERT INTO TmpSqlHist (tmpTime, tmpSql) VALUES("& FixSQL(etime) &", "& FixSQL(sql)&")")
   Pnl.Common.TopParent.Common.ChildControl("eTime").Caption = etime
   Call ClearDropDown(HistDD)
   Call CreateDropDownItems("History")
   Call FillDropDownFromArray(HistDD, History)
   HistDD.ItemIndex=0
   SDB.MessageBox "Statement Successfully Executed in " & etime, mtInformation, Array(mbOK)
End Sub

Sub AddSQLtxt(Btn)
   Dim sqlw,txt
   Set sqlw = Btn.Common.TopParent.Common.ChildControl("sql")
   txt = Trim(Btn.Caption)
   Select Case txt
     Case "="
       sqlw.Text=Ltrim(sqlw.Text) &"="
     Case "Comma"
       sqlw.Text=Ltrim(sqlw.Text) &", "
     Case Else
       sqlw.Text=sqlw.Text & txt &" "
   End Select
End Sub

Sub RemVBS(Btn)
   Dim a,i,sqlw
   Set sqlw = Btn.Common.TopParent.Common.ChildControl("sql")
   a=Split(sqlw.Text,vbcrlf)
   For i=0 to Ubound(a)
      a(i)= DB.OpenSQL("SELECT TRIM("& FixSQL(a(i)) &",'""&_')").StringByIndex(0)
   Next
   sqlw.Text=Join(a,vbcrlf)
End Sub

Sub AddVBS(Btn)
   Dim a,i,sqlw,Spi
   Set Spi  = Btn.Common.TopParent.Common.ChildControl("IndSpaces")
   Set sqlw = Btn.Common.TopParent.Common.ChildControl("sql")
   If Instr(sqlw.Text,"""")>0 Then Exit Sub
   a=Split(sqlw.Text,vbcrlf)
   For i=0 to Ubound(a)
      a(i)= Space(Spi.Value) & """" & a(i)
      If i<Ubound(a) Then
         a(i)= a(i) & " ""&_"
      Else
         a(i)= a(i) & """"
      End If
   Next
   sqlw.Text=Join(a,vbcrlf)
End Sub

Sub AddTable(Btn)
   Dim TablesDD,sqlw,txt
   Set TablesDD = Btn.Common.TopParent.Common.ChildControl("Tables")
   Set sqlw     = Btn.Common.TopParent.Common.ChildControl("sql")
   If TablesDD.ItemIndex = 0 Then Exit Sub
   txt = TablesDD.Text & " "
   sqlw.Text = sqlw.Text & txt
End Sub

Sub AddField(DD)
   Dim TablesDD,Cbx,sqlw,txt
   If DD.ItemIndex = 0 Then Exit Sub
   Set TablesDD = DD.Common.TopParent.Common.ChildControl("Tables")
   Set sqlw     = DD.Common.TopParent.Common.ChildControl("sql")
   Set Cbx      = DD.Common.TopParent.Common.ChildControl("IfTable")
   If Cbx.Checked Then
      txt = TablesDD.Text & "." & DD.Text & " "
   Else
      txt = DD.Text & " "
   End If
   sqlw.Text = sqlw.Text & txt
End Sub

Sub AddFromHist(DD)
   Dim Top,HistRec
   Set Top=DD.Common.TopParent.Common
   Top.ChildControl("Saves").ItemIndex = 0
   Set HistRec = DB.OpenSQL("SELECT * FROM TmpSqlHist WHERE tmpIDnr||' '||tmpSql="& FixSQL(DD.Text))
   Top.ChildControl("Rows").Caption  = HistRec.ValueByName("tmpRows")
   Top.ChildControl("eTime").Caption = HistRec.StringByName("tmpTime")
   Top.ChildControl("sql").Text      = HistRec.StringByName("tmpSql")
   Top.ChildControl("WB").SetHTMLDocument(HistRec.StringByName("tmpHtml"))
   SDB.Objects("holdHTML").RemoveAll
   SDB.Objects("holdHTML").add 0,HistRec.StringByName("tmpHtml")
End Sub

Sub AddFromSave(DD)
   Dim Top,Enabled,SaveRec
   Set Top=DD.Common.TopParent.Common
   Top.ChildControl("History").ItemIndex = 0
   If DD.ItemIndex=0 Then Enabled=False Else Enabled=True
   Top.ChildControl("SaveBtn").Common.Enabled=Enabled
   Top.ChildControl("DelBtn").Common.Enabled=Enabled
   Set SaveRec = DB.OpenSQL("SELECT * FROM TmpSqlSaves WHERE tmpIDnr||' '||tmpName="& FixSQL(DD.Text))
   Top.ChildControl("Rows").Caption  = SaveRec.ValueByName("tmpRows")
   Top.ChildControl("eTime").Caption = SaveRec.StringByName("tmpTime")
   Top.ChildControl("sql").Text      = SaveRec.StringByName("tmpSql")
   Top.ChildControl("WB").SetHTMLDocument(SaveRec.StringByName("tmpHtml"))
   SDB.Objects("holdHTML").RemoveAll
   SDB.Objects("holdHTML").add 0,SaveRec.StringByName("tmpHtml")
End Sub

Sub CreateDropDownItems(What)
  Dim iter,i
  Select Case What
    Case "History"
       Redim History(DB.OpenSQL("SELECT COUNT(*) FROM TmpSqlHist").ValueByIndex(0))
       History(0) = "<History>"
       i=1
       Set iter = DB.OpenSQL("SELECT tmpIDnr||' '||TmpSql FROM TmpSqlHist ORDER BY tmpIDnr DESC LIMIT 200")
       Do While Not iter.EOF
          History(i) = iter.ValueByIndex(0)
          i=i+1
       iter.Next
       Loop
    Case "Saves"
       Redim Saves(DB.OpenSQL("SELECT COUNT(*) FROM TmpSqlSaves").ValueByIndex(0))
       Saves(0) = "<Saves>"
       i=1
       Set iter = DB.OpenSQL("SELECT tmpIDnr||' '||tmpName FROM TmpSqlSaves ORDER BY tmpIDnr DESC")
       Do While Not iter.EOF
          Saves(i) = iter.ValueByIndex(0)
          i=i+1
       iter.Next
       Loop
    Case "Tables"
       Redim Tables(DB.OpenSQL("SELECT Count(*) FROM "&_
                               "(SELECT * FROM sqlite_master UNION ALL "&_
                               " SELECT * FROM sqlite_temp_master) "&_
                               "WHERE type = 'table'").ValueByIndex(0))
       Tables(0) = "<Tables>"
       i=1
       Set iter = DB.OpenSQL("SELECT tbl_name FROM "&_
                             "(SELECT * FROM sqlite_master UNION ALL "&_
                             " SELECT * FROM sqlite_temp_master) "&_
                             "WHERE type = 'table' ORDER BY 1")
       Do While Not iter.EOF
          Tables(i) = iter.ValueByIndex(0)
          i=i+1
       iter.Next
       Loop
    Case "Fields"
       Redim Fields(0)
       Fields(0) = "<Select a Table first>"
    Case "Functions"
       Redim Functions(0)
       Functions(0) = "<Functions>"
    Case "SongData"
       Redim SongData(30)
       SongData(0)  = "<Add data from Selected song>"
       SongData(1)  = "Songs.ID"
       SongData(2)  = "SongTitle"
       SongData(3)  = "ArtistID(s)"
       SongData(4)  = "Artist(s)"
       SongData(5)  = "AlbumID"
       SongData(6)  = "AlbumName"
       SongData(7)  = "AlbumArtistID(s)"
       SongData(8)  = "AlbumArtist(s)"
       SongData(9)  = "GenreID(s)"
       SongData(10) = "Genre(s)"
       SongData(11) = "ComposerID(s)"
       SongData(12) = "Composer(s)"
       SongData(13) = "ConductorID(s)"
       SongData(14) = "Conductor(s)"
       SongData(15) = "LyricistID(s)"
       SongData(16) = "Lyricist(s)"
       SongData(17) = "Rating"
       SongData(18) = "Date"
       SongData(19) = "OriginalYear"
       SongData(20) = "SampleRate"
       SongData(21) = "Bitrate"
       SongData(22) = "Length"
       SongData(23) = "Size"
       SongData(24) = "IDMedia"
       SongData(25) = "ParentFolderID"
       SongData(26) = "IDFolder"
       SongData(27) = "SubFolderID(s)"
       SongData(28) = "DateAdded"
       SongData(29) = "FileModified"
       SongData(30) = "LastPlayed"
  End Select
End Sub

Sub AddSongData(DD)
  Dim list,DB,info,sqlw,txt,SongDataSQL(30)
  Set list = SDB.SelectedSongList
  Set DB   = SDB.Database
  If list.Count=0 Then SDB.MessageBox "Select a song in MM first!", mtInformation, Array(mbOK) : Exit Sub End If
  If DD.ItemIndex = 0 Then Exit Sub
  Set sqlw     = DD.Common.TopParent.Common.ChildControl("sql")
  SongDataSQL(0)  = ""
  SongDataSQL(1)  = list.item(0).ID
  SongDataSQL(2)  = FixSQL(list.item(0).Title)
  SongDataSQL(3)  = "IN (" & DB.OpenSql("SELECT group_concat(IDArtist,', ') FROM ArtistsSongs WHERE PersonType=1 AND IDSong="&list.item(0).ID&" GROUP BY IDSong").StringByIndex(0) & ")"
  SongDataSQL(4)  = FixSQL(list.item(0).ArtistName)
  SongDataSQL(5)  = list.item(0).Album.ID
  SongDataSQL(6)  = FixSQL(list.item(0).AlbumName)
  SongDataSQL(7)  = "IN (" & DB.OpenSql("SELECT group_concat(IDArtist,', ') FROM ArtistsAlbums WHERE IDAlbum="&list.item(0).Album.ID&" GROUP BY IDAlbum").StringByIndex(0) & ")"
  SongDataSQL(8)  = FixSQL(list.item(0).AlbumArtistName)
  SongDataSQL(9)  = "IN (" & DB.OpenSql("SELECT group_concat(IDGenre,', ') FROM GenresSongs WHERE IDSong="&list.item(0).ID&" GROUP BY IDSong").StringByIndex(0) & ")"
  SongDataSQL(10) = FixSQL(list.item(0).Genre)
  SongDataSQL(11) = "IN (" & DB.OpenSql("SELECT group_concat(IDArtist,', ') FROM ArtistsSongs WHERE PersonType=3 AND IDSong="&list.item(0).ID&" GROUP BY IDSong").StringByIndex(0) & ")"
  SongDataSQL(12) = FixSQL(list.item(0).Author)
  SongDataSQL(13) = "IN (" & DB.OpenSql("SELECT group_concat(IDArtist,', ') FROM ArtistsSongs WHERE PersonType=4 AND IDSong="&list.item(0).ID&" GROUP BY IDSong").StringByIndex(0) & ")"
  SongDataSQL(14) = FixSQL(list.item(0).Conductor)
  SongDataSQL(15) = "IN (" & DB.OpenSql("SELECT group_concat(IDArtist,', ') FROM ArtistsSongs WHERE PersonType=5 AND IDSong="&list.item(0).ID&" GROUP BY IDSong").StringByIndex(0) & ")"
  SongDataSQL(16) = FixSQL(list.item(0).Lyricist)
  SongDataSQL(17) = list.item(0).Rating
  SongDataSQL(18) = DB.OpenSql("SELECT Year FROM Songs WHERE ID="&list.item(0).ID).StringByIndex(0)
  SongDataSQL(19) = DB.OpenSql("SELECT OrigYear FROM Songs WHERE ID="&list.item(0).ID).StringByIndex(0)
  SongDataSQL(20) = list.item(0).SampleRate
  SongDataSQL(21) = list.item(0).Bitrate
  SongDataSQL(22) = list.item(0).SongLength
  SongDataSQL(23) = list.item(0).FileLength
  SongDataSQL(24) = list.item(0).Media.ID
  SongDataSQL(25) = DB.OpenSql("SELECT IDParentFolder FROM Folders WHERE ID IN (SELECT IDFolder FROM Songs WHERE ID="&list.item(0).ID &")").StringByIndex(0)
  SongDataSQL(26) = DB.OpenSql("SELECT IDFolder FROM Songs WHERE ID="&list.item(0).ID).StringByIndex(0)
  SongDataSQL(27) = "IN (" & DB.OpenSql("SELECT group_concat(ID,', ') FROM Folders WHERE IDParentFolder IN (SELECT IDFolder FROM Songs WHERE ID="&list.item(0).ID &")").StringByIndex(0) & ")"
  SongDataSQL(28) = DB.OpenSql("SELECT DateAdded FROM Songs WHERE ID="&list.item(0).ID).StringByIndex(0)
  SongDataSQL(29) = DB.OpenSql("SELECT FileModified FROM Songs WHERE ID="&list.item(0).ID).StringByIndex(0)
  SongDataSQL(30) = DB.OpenSql("SELECT LastTimePlayed FROM Songs WHERE ID="&list.item(0).ID).StringByIndex(0)
  
  txt = SongDataSQL(DD.ItemIndex) & " "
  sqlw.Text = sqlw.Text & txt
End Sub

Function FixSQL(SQLString)
  FixSQL= "'" & Replace(SQLString,"'","''") & "'"
End Function

Sub PopuFields(Ctrl)
   Dim table,i,fieldSql,a,DropDown
   On Error Resume Next
   Set DropDown = Ctrl.Common.TopParent.Common.ChildControl("Fields")
   Call ClearDropDown(DropDown)
   If Ctrl.ItemIndex=0 Then
      DropDown.AddItem "<Select a Table first>"
      DropDown.ItemIndex=0
      Exit Sub
   End If
  
   table = Ctrl.Text
  
   fieldSql = DB.OpenSQL("SELECT sql FROM "&_
                         "(SELECT * FROM sqlite_master UNION ALL "&_
                         " SELECT * FROM sqlite_temp_master) "&_
                         "WHERE type = 'table' AND tbl_name='"& table &"'").StringByIndex(0)
   fieldSql = Mid(fieldSql,Instr(fieldSql,"(")+1)
   a = Split(fieldSql,",")
   Redim Fields(Ubound(a)+1)
   Fields(0)="<Fields In " & Table & ">"
   For i=0 To Ubound(a)
      Fields(i+1) = Mid(Trim(a(i)),1,Instr(Trim(a(i))," ")-1)
   Next
  
   Call FillDropDownFromArray(DropDown, Fields)
   DropDown.ItemIndex = 0
End Sub

Sub RunQuery(Pnl)
   Dim t(1),sql,Header,i,j,n,bar,HTML2,MaxRows,WB,HistDD,iter,HTML,Rows,eTime
   Dim RemStart,RemEnd,remov,com,repl1,repl2
  
   sql = Pnl.Common.TopParent.Common.ChildControl("sql").Text
   If sql="" Then Exit Sub
  
   Set HistDD = Pnl.Common.TopParent.Common.ChildControl("History")
   Set WB     = Pnl.Common.TopParent.Common.ChildControl("WB")
   Set Rows   = Pnl.Common.TopParent.Common.ChildControl("Rows")
   Set eTime  = Pnl.Common.TopParent.Common.ChildControl("eTime")
   MaxRows = Pnl.Common.TopParent.Common.ChildControl("MaxRows").Value
   INI.IntValue("SqlViewer","MaxRows") = MaxRows
   Call ClearDropDown(HistDD)

   i=0
   Set Bar = SDB.Progress
   Bar.Text = "Running SQL-statement..."
   t(0) = Timer()
   Set iter = DB.OpenSQL(sql)
   Set Header = iter.FieldNames
   Do While Not iter.EOF
      i=i+1
      If i <= MaxRows Then
         HTML2 = HTML2 & "      <tr" & Style() & ">" & vbcrlf
         If i < 10 then n= "0" & i Else n=i
         HTML2 = HTML2 & "<td>" & MapField(n) & "</td>" & vbcrlf
         For j = 0 To Header.Count-1
            HTML2 = HTML2 & "<td>" & MapField(iter.StringByIndex(j)) & "</td>" & vbcrlf
         Next
         HTML2 = HTML2 & "      </tr>" & vbcrlf
      End If
      iter.Next
   Loop
   t(1) = Timer()
   Set iter = Nothing
   Rows.Caption  = i
   eTime.Caption = FormatNumber(Round(t(1)-t(0),3),3) & " sec"

  HTML = "<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.0 Transitional//EN"">" & vbcrlf
  HTML = HTML & "<html>" & vbcrlf
  HTML = HTML & "  <head>" & vbcrlf
  HTML = HTML & "    <title>" & "SQL Viewer" & "</title>" & vbcrlf
  HTML = HTML & "  </head>" & vbcrlf

  HTML = HTML & "<STYLE TYPE=text/css>" & vbcrlf
  HTML = HTML & "body{font-family:'Verdana',sans-serif; background-color:#FFFFFF; font-size:9pt; color:#000000;}" & vbcrlf
  HTML = HTML & "H1{font-family:'Verdana',sans-serif; font-size:13pt; font-weight:bold; color:#AAAAAA; text-align:left}" & vbcrlf
  HTML = HTML & "P{font-family:'Verdana',sans-serif; font-size:8pt; color:#000000;}" & vbcrlf
  HTML = HTML & "TH{font-family:'Verdana',sans-serif; font-size:9pt; font-weight:bold; color:#000000; border-color:#000000; border-style: solid; border-left-width:0px; border-right-width:0px; border-top-width:0px; border-bottom-width:3px;}" & vbcrlf
  HTML = HTML & "TD{font-family:'Verdana',sans-serif; font-size:8pt; color:#000000; border-color:#000000; border-style: solid; border-left-width:0px; border-right-width:0px; border-top-width:0px; border-bottom-width:1px;}" & vbcrlf
  HTML = HTML & "TD.highlight{font-family:'Verdana',sans-serif; font-size:8pt; background-color:#FFFF77; color:#000000; border-color:#000000; border-style: solid; border-left-width:0px; border-right-width:0px; border-top-width:0px; border-bottom-width:1px;}" & vbcrlf
  HTML = HTML & "TR.dark{background-color:#EEEEEE}" & VbCrLf
  HTML = HTML & "TR.aleft TH{text-align:left}" & vbcrlf
  HTML = HTML & "</STYLE>" & vbcrlf

  HTML = HTML & "  <body>" & vbcrlf
  'HTML = HTML & "    <H1>" & sql & "</H1>" & vbcrlf
  HTML = HTML & "    <table border=""0"" cellspacing=""0"" cellpadding=""4"" width=""100%"">" & vbcrlf
  HTML = HTML & "      <tr class=""aleft"">" & vbcrlf

  HTML = HTML & "        <th>" & "#" & "</th>" & vbcrlf
   For j = 0 To Header.Count-1
      HTML = HTML & "        <th>" & Header.item(j) & "</th>" & vbcrlf
   Next
  HTML = HTML & "      </tr>" & vbcrlf
  HTML = HTML & HTML2  
  HTML = HTML & "    </table>" & vbcrlf
  HTML = HTML & "  </body>" & vbcrlf
  HTML = HTML & "</html>" & vbcrlf
  WB.SetHTMLDocument( HTML)
  SDB.Objects("holdHTML").RemoveAll
  SDB.Objects("holdHTML").add 0,HTML

   DB.ExecSQL("INSERT INTO TmpSqlHist (tmpRows, tmpTime, tmpHtml, tmpSql) "&_
              "VALUES("& Rows.Caption &", '"& eTime.Caption &"', "& FixSQL(HTML) &", "& FixSQL(sql) &")")
   Call CreateDropDownItems("History")
   Call FillDropDownFromArray(HistDD, History)
   HistDD.ItemIndex=0
   If Not bar Is Nothing Then Set bar = Nothing
End Sub

Sub OnClose(Btn)
   Set SDB.Objects("SQLThingy") = Nothing
   Set SDB.Objects("holdHTML") = Nothing
   DB.ExecSQL("DELETE FROM TmpSqlHist WHERE tmpIDnr NOT IN (SELECT tmpIDnr FROM TmpSqlHist ORDER BY tmpIDnr DESC LIMIT 200)")
End Sub

Function Style()
  styleOn = Not styleOn
  If styleOn Then
    Style = ""
  Else
    Style = " class=""Dark"""
  End If
End Function

Function MapXML(original)
  Dim hold
  hold = Replace(original, "&", "&amp;")
  hold = Replace(hold, "  ", "&nbsp; ")
  hold = Replace(hold, "<", "&lt;")
  hold = Replace(hold, ">", "&gt;")
  hold = Replace(hold, """", "&quot;")
  Dim i
  i=1
  While i<=Len(hold)
    If (AscW(Mid(hold, i, 1))>127) Then
      hold = Mid(hold, 1, i-1)+"&#"+CStr(AscW(Mid(hold, i, 1)))+";"+Mid(hold, i+1)
    End If
    i=i+1
  WEnd
  MapXML = hold
End Function

Function MapField(fld)
  If fld="" Then
    MapField = "&nbsp;"
  Else
    MapField = MapXML(fld)
  End If
End Function

Function CreateLbl(Owner,X,Y,W,H,Caption,ControlName)
    Set CreateLbl = UI.NewLabel(Owner)
    CreateLbl.Common.ControlName = ControlName
    CreateLbl.Common.SetRect X,Y,W,H
    CreateLbl.Caption = Caption
End Function

Function CreateBtn(Owner,X,Y,W,H,Caption,ControlName,OnClickFunc,Anchors,Hint,ModalResult,DefaultCancel,Enabled)
    Set CreateBtn = UI.NewButton(Owner)
    CreateBtn.Common.SetRect X,Y,W,H
    CreateBtn.Common.ControlName = ControlName
    CreateBtn.Caption = Caption
    If not Anchors="" Then CreateBtn.Common.Anchors = Anchors
    CreateBtn.UseScript = Script.ScriptPath ' benzzon // SDB.ApplicationPath & "Scripts\SqlViewer.vbs"
    CreateBtn.OnClickFunc = OnClickFunc
    CreateBtn.Common.Hint = Hint
    If ModalResult<>"" Then CreateBtn.ModalResult = ModalResult
    If DefaultCancel<>"" Then
      If DefaultCancel="Default" Then CreateBtn.Default = True
      If DefaultCancel="Cancel"  Then CreateBtn.Cancel  = True
    End If
    CreateBtn.Common.Enabled = Enabled
End Function

Function CreateCbx(Owner,X,Y,W,H,Caption,ControlName,Hint,Checked,OnClickName)
    Set CreateCbx = UI.NewCheckBox(Owner)
    CreateCbx.Common.ControlName = ControlName
    CreateCbx.Caption = Caption
    CreateCbx.Common.SetRect X,Y,W,H
    CreateCbx.Common.Hint = Hint
    CreateCbx.Checked = Checked
    If Not OnClickName="" Then Script.RegisterEvent CreateCbx.Common, "OnClick", OnClickName
End Function

Function CreateDrd(Owner,X,Y,W,H,ControlName,Anchors,ItemIndex,What,SourceArray,OnSelectFunc,Hint)
  Set CreateDrd = UI.NewDropDown(Owner)
  CreateDrd.Common.SetRect X,Y,W,H
  CreateDrd.Common.ControlName = ControlName
  CreateDropDownItems What
  FillDropDownFromArray CreateDrd.Common.ChildControl(ControlName), SourceArray
  CreateDrd.ItemIndex = ItemIndex
  If Not Anchors="" Then CreateDrd.Common.Anchors = Anchors
  CreateDrd.Style = 2
  CreateDrd.UseScript = Script.ScriptPath ' benzzon // SDB.ApplicationPath & "Scripts\SqlViewer.vbs"
  CreateDrd.OnSelectFunc = OnSelectFunc
  CreateDrd.Common.Hint = Hint
End Function

Sub FillDropDownFromArray(DropDown, SourceArray)
  Dim i
  For i=0 To UBound(SourceArray)
    DropDown.AddItem SourceArray(i)
  Next
End Sub

Sub ClearDropDown(DropDown)
   Dim i
   For i=DropDown.ItemCount-1 To 0 Step -1
      DropDown.DeleteItem i
   Next
End Sub

Sub Install()
   'Add scripts.ini entries
   Dim inip : inip = SDB.ApplicationPath&"Scripts\Scripts.ini"
   Dim inif : Set inif = SDB.Tools.IniFileByPath(inip)
   If Not (inif Is Nothing) Then  
        inif.StringValue("SqlViewer","Filename") = "SqlViewer.vbs"
      inif.StringValue("SqlViewer","Procname") = "SqlViewer"
      inif.StringValue("SqlViewer","Order") = "100"
      inif.StringValue("SqlViewer","DisplayName") = "SQL-Viewer"
      inif.StringValue("SqlViewer","Description") = "Run SQL Statement Within MM Text"
      inif.StringValue("SqlViewer","Language") = "VBScript"
      inif.StringValue("SqlViewer","ScriptType") = "0"
      inif.StringValue("SqlViewer","Shortcut") = "CTRL+F9"
      SDB.RefreshScriptItems
   End If
   'Add entries to Mediamonkey.ini
   If INI.StringValue("SqlViewer","MaxRows")   = "" Then INI.IntValue("SqlViewer","MaxRows") = 50
   If INI.StringValue("SqlViewer","IndSpaces") = "" Then INI.IntValue("SqlViewer","MaxRows") = 15
   If INI.StringValue("SqlViewer","AddTable")  = "" Then INI.BoolValue("SqlViewer","AddTable") = False
End Sub