Imports System.Data.SqlClient
Imports System.Reflection
Imports System.Windows.Forms
Imports com.sun.org.apache.xerces.internal.impl
Imports com.sun.xml.internal.rngom

Public Class cMessenger

    Public Shared NEW_MESSGE As Boolean = False
    Public Shared UNREAD_MESAGES As Integer = 0

    Shared SQL As New SQL

    Public Shared Function GEN_NEW_CHAT(chat_name As String, MaIds As List(Of Integer), Optional ByRef CHAT As VERAG_PROG_ALLGEMEIN.cMessenger.cMessenger_Chat = Nothing, Optional chat_art As String = "CHAT", Optional chat_AvisoId As Integer = -1, Optional chat_SendungsId As Integer = -1) As Boolean
        CHAT = New VERAG_PROG_ALLGEMEIN.cMessenger.cMessenger_Chat
        CHAT.chat_erstelltAm = Now
        If chat_art <> "" Then CHAT.chat_art = chat_art
        If chat_AvisoId > 0 Then CHAT.chat_AvisoId = chat_AvisoId
        If chat_SendungsId > 0 Then CHAT.chat_SendungsId = chat_SendungsId

        CHAT.chat_erstelltMaId = VERAG_PROG_ALLGEMEIN.cAllgemein.USRID
        CHAT.chat_name = chat_name

        For Each maId In MaIds
            Dim MB As New VERAG_PROG_ALLGEMEIN.cMessenger.cMessenger_ChatMembers(CHAT.chat_id, maId)
            MB.chatMb_maId = maId
            CHAT.CHAT_MEMBERS.Add(MB)
        Next
        Return CHAT.SAVE(True)

    End Function



    Public Shared Function CHECK_EXISTS(MaId As Integer, Optional ByRef toChatID As Integer = -1) As Boolean
        Dim sqlStr = "Select TOP 1 chat_id FROM [tblMessenger_Chat]  inner join tblMessenger_ChatMembers On chatMb_chatId=chat_id  where chat_name='' AND [chat_aktiv]=1
                        And (SELECT COUNT(*) FROM tblMessenger_ChatMembers WHERE chatMb_chatId=chat_id And chatMb_maId='" & VERAG_PROG_ALLGEMEIN.cAllgemein.USRID & "' )  >0
                        And (SELECT COUNT(*) FROM tblMessenger_ChatMembers WHERE chatMb_chatId=chat_id And chatMb_maId='" & MaId & "' )  >0
                        order by chat_id DESC"

        toChatID = SQL.getValueTxtBySql(sqlStr, "ADMIN",,, -1)
        Return (toChatID > 0)
    End Function


    Public Shared Function GET_NewMSG_COUNT(Optional maId = -1) As Integer
        If maId < 0 Then maId = VERAG_PROG_ALLGEMEIN.cAllgemein.USRID
        Return SQL.getValueTxtBySql("SELECT isnull(COUNT(*),0) FROM tblMessenger_ChatMessages INNER JOIN tblMessenger_ChatMessageStatus ON chatMgSt_chatMsgId=chatMg_id WHERE chatMgSt_MaId=" & VERAG_PROG_ALLGEMEIN.cAllgemein.USRID & " AND chatMgSt_gelesen=0 and chatMg_chatId in (SELECT [chatMb_chatId] FROM [tblMessenger_ChatMembers] where [chatMb_maId] = " & maId & ")", "ADMIN",,, 0)
    End Function
    Public Shared Function GET_NewMSG_COUNT_CHATID(maId, chat_Id) As Integer
        If maId < 0 Then maId = VERAG_PROG_ALLGEMEIN.cAllgemein.USRID
        Return SQL.getValueTxtBySql("SELECT isnull(COUNT(*),0) FROM tblMessenger_ChatMessages INNER JOIN tblMessenger_ChatMessageStatus ON chatMgSt_chatMsgId=chatMg_id WHERE chatMgSt_MaId=" & maId & " AND chatMgSt_gelesen=0  AND chatMg_chatId='" & chat_Id & "' AND (SELECT COUNT(*) FROM tblMessenger_ChatMembers WHERE chatMB_chatId='" & chat_Id & "'AND chatMB_maId=" & maId & ")>0", "ADMIN",,, 0)
    End Function

    Public Shared Function SET_LKWCHAT_INAKTIV(AvisoId) As Integer
        Return SQL.doSQL("UPDATE tblMessenger_Chat SET chat_aktiv=0 WHERE chat_AvisoId='" & AvisoId & "' AND chat_art='LKW_CHAT' ", "ADMIN")
    End Function
    Public Shared Function SET_LKWCHAT_AKTIV(AvisoId) As Integer
        Return SQL.doSQL("UPDATE tblMessenger_Chat SET chat_aktiv=1 WHERE chat_AvisoId='" & AvisoId & "' AND chat_art='LKW_CHAT' ", "ADMIN")
    End Function
    Public Shared Function GET_NewMSG_COUNT_ART(maId, chat_art) As Integer
        If maId < 0 Then maId = VERAG_PROG_ALLGEMEIN.cAllgemein.USRID
        'Return SQL.getValueTxtBySql("SELECT isnull(COUNT(*),0) FROM tblMessenger_ChatMessages INNER JOIN tblMessenger_Chat on chat_id=chatMg_chatId INNER JOIN tblMessenger_ChatMessageStatus ON chatMgSt_chatMsgId=chatMg_id WHERE chatMgSt_MaId=" & maId & "  AND chatMgSt_gelesen=0  AND chat_art='" & chat_art & "' AND (SELECT COUNT(*) FROM tblMessenger_ChatMembers WHERE chatMB_chatId=chat_id AND chatMB_maId=" & maId & ")>0", "ADMIN",,, 0)
        Return SQL.getValueTxtBySql("SELECT isnull(COUNT(*),0) FROM tblMessenger_ChatMessages INNER JOIN tblMessenger_Chat on chat_id=chatMg_chatId INNER JOIN tblMessenger_ChatMessageStatus ON chatMgSt_chatMsgId=chatMg_id WHERE chatMgSt_MaId=" & maId & "  AND chatMgSt_gelesen=0  AND chat_art='" & chat_art & "' AND chatMg_chatId in (SELECT [chatMb_chatId] FROM [tblMessenger_ChatMembers] where [chatMb_maId] = " & maId & " and chatMB_chatId=chat_id)", "ADMIN",,, 0)
    End Function
    Public Shared Function GET_NewMSG_COUNT_ART_INAKTIV(maId, chat_art) As Integer
        If maId < 0 Then maId = VERAG_PROG_ALLGEMEIN.cAllgemein.USRID
        Return SQL.getValueTxtBySql("SELECT isnull(COUNT(*),0) FROM tblMessenger_ChatMessages INNER JOIN tblMessenger_Chat on chat_id=chatMg_chatId INNER JOIN tblMessenger_ChatMessageStatus ON chatMgSt_chatMsgId=chatMg_id WHERE chatMgSt_MaId=" & maId & "   AND chatMgSt_gelesen=0 AND chat_aktiv=0  AND chat_art='" & chat_art & "' AND (SELECT COUNT(*) FROM tblMessenger_ChatMembers WHERE chatMB_chatId=chat_id AND chatMB_maId=" & maId & ")>0", "ADMIN",,, 0)
    End Function

    Public Shared Function GET_NewMSG_COUNT_AVISOID(AvisoId As Integer) As Integer
        'Dim chat_id = SQL.DLookup("chat_id", "tblMessenger_ChatMembers inner join tblMessenger_Chat on chat_id=chatMb_chatId", "chat_AvisoId='" & AvisoId & "' and [chatMb_maId]='" & VERAG_PROG_ALLGEMEIN.cAllgemein.USRID & "'", "ADMIN", -1)
        Dim chat_id = SQL.DLookup("chat_id", "tblMessenger_Chat ", "chat_AvisoId='" & AvisoId & "'  AND (chat_SendungsId is null or chat_SendungsId<=0)", "ADMIN", -1)
        If chat_id > 0 Then 'Ich bin Member vom Chat.
            '  Return GET_NewMSG_COUNT_CHATID(VERAG_PROG_ALLGEMEIN.cAllgemein.USRID, chat_id)
            ' Else
            ' MsgBox(SQL.DLookup("isnull(count(*),0)", "tblMessenger_ChatMessages inner join tblMessenger_Chat on chat_id=chatMg_chatId", "chat_AvisoId='" & AvisoId & "'", "ADMIN", 0))
            Return SQL.DLookup("isnull(count(*),0)", "tblMessenger_ChatMessages inner join tblMessenger_Chat on chat_id=chatMg_chatId", "chat_AvisoId='" & AvisoId & "'  AND (chat_SendungsId is null or chat_SendungsId<=0) ", "ADMIN", 0)
        End If
    End Function
    Public Shared Function GET_NewMSG_COUNT_SendungsID(SendungsID As Integer) As Integer
        Dim chat_id = SQL.DLookup("chat_id", "tblMessenger_Chat ", "chat_SendungsId='" & SendungsID & "'", "ADMIN", -1)
        If chat_id > 0 Then 'Ich bin Member vom Chat.
            ' Return GET_NewMSG_COUNT_CHATID(VERAG_PROG_ALLGEMEIN.cAllgemein.USRID, chat_id)
            '   Else
            Return SQL.DLookup("isnull(count(*),0)", "tblMessenger_ChatMessages inner join tblMessenger_Chat on chat_id=chatMg_chatId", "chat_SendungsId='" & SendungsID & "'", "ADMIN", 0)
        End If
    End Function
    Public Shared Function isACTIVE_AVISOID(AvisoId As Integer) As Boolean
        Dim chat_idCNT = SQL.DLookup("COUNT(*)", "tblMessenger_Chat", "chat_AvisoId='" & AvisoId & "' AND (SendungsID is null or SendungsID<=0)", "ADMIN", -1)
        If chat_idCNT > 0 Then 'Ich bin Member vom Chat.
            Return True
        Else
            Return False
        End If
    End Function
    Public Shared Function isACTIVE_SendungsID(SendungsID As Integer) As Boolean
        Dim chat_idCNT = SQL.DLookup("COUNT(*)", "tblMessenger_Chat", "chat_SendungsId='" & SendungsID & "'", "ADMIN", -1)
        If chat_idCNT > 0 Then 'Ich bin Member vom Chat.
            Return True
        Else
            Return False
        End If
    End Function

    Public Shared Function GET_CHAT_LIST() As List(Of cMessenger_Chat)
        Dim LIST As New List(Of cMessenger_Chat)
        Dim dt = SQL.loadDgvBySql("SELECT [chat_id] FROM [tblMessenger_Chat] WHERE (SELECT COUNT(*) FROM tblMessenger_ChatMembers WHERE chatMB_chatId=chat_id AND chatMB_maId=" & VERAG_PROG_ALLGEMEIN.cAllgemein.USRID & ")>0", "ADMIN")

        For Each r In dt.Rows
            Dim CHAT As New VERAG_PROG_ALLGEMEIN.cMessenger.cMessenger_Chat(r("chat_id"), 200)
            LIST.Add(CHAT)
        Next
        Return LIST

    End Function

    Public Class cMessenger_Chat

        Property chat_id As Integer = -1
        Property chat_name As String
        Property chat_art As String = "CHAT"
        Property chat_erstelltAm As Date = Now
        Property chat_erstelltMaId As Integer
        Property chat_AvisoId As Integer = -1
        Property chat_SendungsId As Integer = -1
        Property chat_aktiv As Boolean = True
        Property chat_freigegeben As Boolean = True

        Public CHAT_MEMBERS As New List(Of cMessenger_ChatMembers)
        Public CHAT_MESSAGES As New List(Of cMessenger_ChatMessages)
        Dim SQL As New SQL

        Sub New()
            Me.chat_erstelltMaId = VERAG_PROG_ALLGEMEIN.cAllgemein.USRID
            Me.chat_erstelltAm = Now
            LOAD()
        End Sub


        Sub New(chat_id As Integer, topMax As String, Optional dateTmp As Object = Nothing)
            Me.chat_id = chat_id
            Me.chat_erstelltMaId = VERAG_PROG_ALLGEMEIN.cAllgemein.USRID
            Me.chat_erstelltAm = Now
            LOAD(topMax, dateTmp)
        End Sub
        Sub New(chat_AvisoId As Integer, chat_SendungsId As Integer, chat_art As String, Optional topMax As String = "", Optional dateTmp As Object = Nothing)
            Me.chat_id = chat_id
            Me.chat_erstelltMaId = VERAG_PROG_ALLGEMEIN.cAllgemein.USRID
            Me.chat_erstelltAm = Now
            Me.chat_art = "LKW_CHAT"
            If chat_SendungsId > 0 Then Me.chat_art = "SND_CHAT"
            LOAD_ByLKW(chat_AvisoId, chat_SendungsId, chat_art, topMax, dateTmp)

        End Sub



        Shared Function openLKW_Chat(Aviso As cAviso) As Boolean
            Dim CHAT = New VERAG_PROG_ALLGEMEIN.cMessenger.cMessenger_Chat(Aviso.AvisoID, -1, "LKW_CHAT")

            If CHAT.chat_id <= 0 Then
                'Neuer Chat
                Dim chatName = Aviso.LKW_Nr & " (LKW-Id: " & Aviso.AvisoID & ")"
                '"LKW CHAT: " &

                Dim MB_LIST As New List(Of Integer)
                MB_LIST.Add(VERAG_PROG_ALLGEMEIN.cAllgemein.USRID)

                VERAG_PROG_ALLGEMEIN.cMessenger.GEN_NEW_CHAT(chatName, MB_LIST, CHAT, "LKW_CHAT", Aviso.AvisoID, -1)

            End If
            If CHAT IsNot Nothing Then

                If Not CHAT.CHAT_MEMBERS.Exists(Function(x) x.chatMb_maId = VERAG_PROG_ALLGEMEIN.cAllgemein.USRID) Then
                    If vbYes <> MsgBox("Möchten Sie dem LKW Chat beitreten?", vbYesNoCancel) Then
                        Return False
                    Else 'weiter...
                        Dim MB As New VERAG_PROG_ALLGEMEIN.cMessenger.cMessenger_ChatMembers(CHAT.chat_id, VERAG_PROG_ALLGEMEIN.cAllgemein.USRID)
                        MB.chatMb_maId = VERAG_PROG_ALLGEMEIN.cAllgemein.USRID
                        CHAT.CHAT_MEMBERS.Add(MB)
                        If Not CHAT.SAVE_MEMBERS Then
                            MsgBox("Fehler beim Hinzufügen!")
                            Return False 'Fehler
                        End If
                    End If
                End If

                '  Me.Cursor = Cursors.WaitCursor
                'For Each openForm In Application.OpenForms()
                '    If TypeOf (openForm) Is VERAG_PROG_ALLGEMEIN.frmMessenger Then
                '        CType(openForm, VERAG_PROG_ALLGEMEIN.frmMessenger).WindowState = FormWindowState.Normal
                '        CType(openForm, VERAG_PROG_ALLGEMEIN.frmMessenger).BringToFront()
                '        Me.Cursor = Cursors.Default : Exit Sub
                '    End If
                'Next

                Dim f As New VERAG_PROG_ALLGEMEIN.frmMessenger()
                f.Location = Cursor.Position
                f.AvisoId = Aviso.AvisoID
                f.Show()

                Return True
            End If
            Return False
        End Function
        Shared Function openSND_Chat(Aviso As cAviso, Sendung As cSendungen) As Boolean
            Dim CHAT = New VERAG_PROG_ALLGEMEIN.cMessenger.cMessenger_Chat(Aviso.AvisoID, Sendung.tblSnd_SendungID, "SND_CHAT")


            If CHAT.chat_id <= 0 Then
                'Neuer Chat
                Dim chatName = Sendung.FilialenNr & "/" & Sendung.AbfertigungsNr & " (" & Aviso.LKW_Nr & ")"
                '"SND CHAT: " &

                Dim MB_LIST As New List(Of Integer)
                MB_LIST.Add(VERAG_PROG_ALLGEMEIN.cAllgemein.USRID)

                VERAG_PROG_ALLGEMEIN.cMessenger.GEN_NEW_CHAT(chatName, MB_LIST, CHAT, "SND_CHAT", Aviso.AvisoID, Sendung.tblSnd_SendungID)

            End If
            If CHAT IsNot Nothing Then

                If Not CHAT.CHAT_MEMBERS.Exists(Function(x) x.chatMb_maId = VERAG_PROG_ALLGEMEIN.cAllgemein.USRID) Then
                    If vbYes <> MsgBox("Möchten Sie dem SENDUNGS-Chat beitreten?", vbYesNoCancel) Then
                        Return False
                    Else 'weiter...
                        Dim MB As New VERAG_PROG_ALLGEMEIN.cMessenger.cMessenger_ChatMembers(CHAT.chat_id, VERAG_PROG_ALLGEMEIN.cAllgemein.USRID)
                        MB.chatMb_maId = VERAG_PROG_ALLGEMEIN.cAllgemein.USRID
                        CHAT.CHAT_MEMBERS.Add(MB)
                        If Not CHAT.SAVE_MEMBERS Then
                            MsgBox("Fehler beim Hinzufügen!")
                            Return False 'Fehler
                        End If
                    End If
                End If

                '  Me.Cursor = Cursors.WaitCursor
                'For Each openForm In Application.OpenForms()
                '    If TypeOf (openForm) Is VERAG_PROG_ALLGEMEIN.frmMessenger Then
                '        CType(openForm, VERAG_PROG_ALLGEMEIN.frmMessenger).WindowState = FormWindowState.Normal
                '        CType(openForm, VERAG_PROG_ALLGEMEIN.frmMessenger).BringToFront()
                '        Me.Cursor = Cursors.Default : Exit Sub
                '    End If
                'Next

                Dim f As New VERAG_PROG_ALLGEMEIN.frmMessenger()
                f.Location = Cursor.Position
                f.AvisoId = Aviso.AvisoID
                f.SendungID = Sendung.tblSnd_SendungID
                f.Show()

                Return True
            End If
            Return False
        End Function
        Public Function getParameterList() As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable)
            Dim list As New List(Of VERAG_PROG_ALLGEMEIN.SQLVariable)
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("chat_id", chat_id,, True))

            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("chat_name", chat_name))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("chat_art", chat_art))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("chat_erstelltAm", chat_erstelltAm))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("chat_erstelltMaId", chat_erstelltMaId))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("chat_AvisoId", chat_AvisoId))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("chat_SendungsId", chat_SendungsId))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("chat_aktiv", chat_aktiv))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("chat_freigegeben", chat_freigegeben))

            Return list
        End Function



        Public Function SAVE(saveAll As Boolean) As Boolean
            Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()
            Dim sqlstr = " BEGIN TRAN IF EXISTS(SELECT * FROM tblMessenger_Chat WHERE chat_id=@chat_id) " &
                       " BEGIN " & getUpdateCmd() & " End " &
                       " Else " &
                       " BEGIN " & getInsertCmd() & " End " &
                       " commit tran "

            chat_id = SQL.doSQLVarListID(chat_id, sqlstr, "ADMIN", , list)

            If saveAll Then
                SAVE_MEMBERS()
            End If

            Return chat_id > 0
        End Function

        Public Sub LOAD(Optional topMax As String = "", Optional dateTmp As Object = Nothing)
            Try
                Using conn As SqlConnection = SQL.GetNewOpenConnectionADMIN()
                    Using cmd As New SqlCommand("Select * FROM tblMessenger_Chat WHERE chat_id=@chat_id  ", conn)
                        cmd.Parameters.AddWithValue("@chat_id", chat_id)
                        Dim dr = cmd.ExecuteReader()
                        If dr.Read Then
                            For Each li In getParameterList()
                                Dim propInfo As PropertyInfo = Me.GetType.GetProperty(li.Scalarvariable)

                                If dr.Item(li.Text) Is DBNull.Value Then
                                    propInfo.SetValue(Me, Nothing)
                                Else
                                    propInfo.SetValue(Me, dr.Item(li.Text))
                                End If

                            Next
                            Me.LOAD_MEMBERS()
                            If dateTmp Is Nothing Then
                                Me.LOAD_MESSAGES_NEW(topMax)
                            Else
                                Me.LOAD_MESSAGES_DATE(dateTmp)
                            End If

                        End If
                        dr.Close()
                    End Using
                End Using
            Catch ex As Exception
                MsgBox("Fehler in der Funktion '" & System.Reflection.MethodInfo.GetCurrentMethod.Name & "'" & vbNewLine & vbNewLine & ex.Message & vbNewLine & vbNewLine & ex.StackTrace)
            End Try
        End Sub


        Public Sub LOAD_ByLKW(chat_AvisoId As Integer, chat_SendungsId As Integer, chat_art As String, Optional topMax As String = "", Optional dateTmp As Object = Nothing)
            Try
                Using conn As SqlConnection = SQL.GetNewOpenConnectionADMIN()
                    Using cmd As New SqlCommand("Select * FROM tblMessenger_Chat WHERE chat_AvisoId=@chat_AvisoId " & If(chat_SendungsId > 0, " AND chat_SendungsId=@chat_SendungsId ", "") & " AND chat_art='" & chat_art & "'", conn)
                        cmd.Parameters.AddWithValue("@chat_AvisoId", chat_AvisoId)
                        cmd.Parameters.AddWithValue("@chat_SendungsId", chat_SendungsId)
                        cmd.Parameters.AddWithValue("@chat_art", chat_art)

                        Dim dr = cmd.ExecuteReader()
                        If dr.Read Then
                            For Each li In getParameterList()
                                Dim propInfo As PropertyInfo = Me.GetType.GetProperty(li.Scalarvariable)

                                If dr.Item(li.Text) Is DBNull.Value Then
                                    propInfo.SetValue(Me, Nothing)
                                Else
                                    propInfo.SetValue(Me, dr.Item(li.Text))
                                End If

                            Next

                            Me.LOAD_MEMBERS()
                            If dateTmp Is Nothing Then
                                Me.LOAD_MESSAGES_NEW()
                            Else
                                Me.LOAD_MESSAGES_DATE(dateTmp)
                            End If

                        End If
                        dr.Close()
                    End Using
                End Using
            Catch ex As Exception
                MsgBox("Fehler in der Funktion '" & System.Reflection.MethodInfo.GetCurrentMethod.Name & "'" & vbNewLine & vbNewLine & ex.Message & vbNewLine & vbNewLine & ex.StackTrace)
            End Try
        End Sub



        Public Function SAVE_MEMBERS() As Boolean
            Try
                DELETE_MEMBERS()
                For Each MB In Me.CHAT_MEMBERS
                    MB.chatMb_chatId = Me.chat_id
                    MB.SAVE()
                Next
                Return True
            Catch ex As Exception
                MsgBox("Fehler in der Funktion '" & System.Reflection.MethodInfo.GetCurrentMethod.Name & "'" & vbNewLine & vbNewLine & ex.Message & vbNewLine & vbNewLine & ex.StackTrace)
                Return False
            End Try
        End Function

        Public Function READ_ALL_MESSAGES() As Boolean
            Dim sqlstr = "UPDATE tblMessenger_ChatMessageStatus SET chatMgSt_gelesen=1, chatMgSt_datetimeGelesen = GETDATE(), chatMgSt_gelesenVonMaId = " & VERAG_PROG_ALLGEMEIN.cAllgemein.USRID & " FROM [tblMessenger_Chat] INNER JOIN tblMessenger_ChatMessages ON [chat_id]=chatMg_chatId  INNER JOIN tblMessenger_ChatMessageStatus ON chatMgSt_chatMsgId=chatMg_id WHERE chat_id=" & Me.chat_id & " AND chatMgSt_MaId=" & VERAG_PROG_ALLGEMEIN.cAllgemein.USRID & " AND chatMgSt_gelesen=0  "
            Return SQL.doSQL(sqlstr, "ADMIN")
        End Function

        Public Function DELETE_MEMBERS() As Boolean 'obj As Object, tablename As String, where As String) As Boolean
            Dim sqlstr = " DELETE FROM [tblMessenger_ChatMembers] WHERE chatMb_chatId=" & Me.chat_id
            Return SQL.doSQL(sqlstr, "ADMIN")
        End Function
        Public Sub LOAD_MEMBERS()
            Try
                Me.CHAT_MEMBERS.Clear()
                Using conn As SqlConnection = SQL.GetNewOpenConnectionADMIN()
                    Using cmd As New SqlCommand("SELECT * FROM tblMessenger_ChatMembers WHERE chatMb_chatId=@chat_id  ", conn)
                        cmd.Parameters.AddWithValue("@chat_id", chat_id)
                        Dim dr = cmd.ExecuteReader()
                        While dr.Read
                            Dim MB As New cMessenger_ChatMembers(Me.chat_id, dr.Item("chatMb_maId"))
                            Me.CHAT_MEMBERS.Add(MB)
                        End While
                        dr.Close()
                    End Using
                End Using
            Catch ex As Exception
                MsgBox("Fehler in der Funktion '" & System.Reflection.MethodInfo.GetCurrentMethod.Name & "'" & vbNewLine & vbNewLine & ex.Message & vbNewLine & vbNewLine & ex.StackTrace)
            End Try
        End Sub
        Public Sub LOAD_MESSAGES(Optional top As Integer = 100)
            Try
                Me.CHAT_MESSAGES.Clear()
                Using conn As SqlConnection = SQL.GetNewOpenConnectionADMIN()
                    ' Using cmd As New SqlCommand("SELECT chatMg_id,chatMg_chatId,chatMg_maId,chatMg_maName,chatMg_maFirma,chatMg_datetime,chatMg_type,chatMg_text,chatMg_anhang_docId,chatMg_referenz_AvisoId,chatMg_referenz_SendungsId,chatMg_referenz_KundenNr FROM(SELECT TOP " & top & " chatMg_id,chatMg_chatId,chatMg_maId,chatMg_maName,chatMg_maFirma,chatMg_datetime,chatMg_type,chatMg_text,chatMg_anhang_docId,chatMg_referenz_AvisoId,chatMg_referenz_SendungsId,chatMg_referenz_KundenNr FROM [tblMessenger_ChatMessages] WHERE chatMg_chatId=@chat_id  order by chatMg_datetime desc) as T order by chatMg_datetime asc", conn)

                    Using cmd As New SqlCommand("SELECT TOP (@top) chatMg_id,chatMg_chatId,chatMg_maId,chatMg_maName,chatMg_maFirma,chatMg_datetime,chatMg_type,chatMg_text,chatMg_anhang_docId,chatMg_referenz_AvisoId,chatMg_referenz_SendungsId,chatMg_referenz_KundenNr FROM tblMessenger_ChatMessages WHERE chatMg_chatId = @chat_id ORDER BY chatMg_datetime DESC", conn)

                        cmd.Parameters.AddWithValue("@chat_id", chat_id)
                        cmd.Parameters.AddWithValue("@top", top)
                        Dim dr = cmd.ExecuteReader()
                        While dr.Read
                            'Dim MSG As New cMessenger_ChatMessages(dr.Item("chatMg_id")) '  ----> 100 messages = 101 SQL calls
                            'Hier werden die einzelnen MSg-Obj nicht mehr per SQL geladen, sondern direkt als Objekt übergeben -> schneller!
                            Dim MSG As New cMessenger_ChatMessages(dr.Item("chatMg_id"), dr.Item("chatMg_chatId"), dr.Item("chatMg_maId"), dr.Item("chatMg_datetime"), dr.Item("chatMg_maName"), dr.Item("chatMg_maFirma"), dr.Item("chatMg_type"), dr.Item("chatMg_text"), IIf(IsDBNull(dr.Item("chatMg_anhang_docId")), Nothing, dr.Item("chatMg_anhang_docId")), IIf(IsDBNull(dr.Item("chatMg_referenz_AvisoId")), Nothing, dr.Item("chatMg_referenz_AvisoId")), IIf(IsDBNull(dr.Item("chatMg_referenz_SendungsId")), Nothing, dr.Item("chatMg_referenz_SendungsId")), dr.Item("chatMg_referenz_KundenNr")) 'Me.chat_id, dr.Item("chatMb_maId")) 'yxc
                            Me.CHAT_MESSAGES.Add(MSG)
                        End While
                        dr.Close()
                    End Using
                End Using

                Me.CHAT_MESSAGES.Reverse()

            Catch ex As Exception
                MsgBox("Fehler in der Funktion '" & System.Reflection.MethodInfo.GetCurrentMethod.Name & "'" & vbNewLine & vbNewLine & ex.Message & vbNewLine & vbNewLine & ex.StackTrace)
            End Try
        End Sub

        Public Sub LOAD_MESSAGES_NEW(Optional top As Integer = 100)
            Try
                Me.CHAT_MESSAGES.Clear()

                Using conn As SqlConnection = SQL.GetNewOpenConnectionADMIN()
                    Using cmd As New SqlCommand(
                        "SELECT TOP (@top) chatMg_id, chatMg_chatId, chatMg_maId, chatMg_maName, chatMg_maFirma, chatMg_datetime, chatMg_type, chatMg_text, chatMg_anhang_docId, chatMg_referenz_AvisoId, chatMg_referenz_SendungsId, chatMg_referenz_KundenNr
                 FROM tblMessenger_ChatMessages
                 WHERE chatMg_chatId = @chat_id
                 ORDER BY chatMg_datetime DESC", conn)

                        cmd.Parameters.AddWithValue("@chat_id", chat_id)
                        cmd.Parameters.AddWithValue("@top", top)

                        Using dr As SqlDataReader = cmd.ExecuteReader()
                            While dr.Read()
                                Dim chatMg_id As Integer? = SafeInt(dr("chatMg_id"))
                                Dim chatMg_chatId As Integer? = SafeInt(dr("chatMg_chatId"))
                                Dim chatMg_maId As Integer? = SafeInt(dr("chatMg_maId"))
                                Dim chatMg_type As String = If(IsDBNull(dr("chatMg_type")), "", dr("chatMg_type").ToString())
                                Dim chatMg_anhang_docId As Integer? = SafeInt(dr("chatMg_anhang_docId"))
                                Dim chatMg_referenz_AvisoId As Integer? = SafeInt(dr("chatMg_referenz_AvisoId"))
                                Dim chatMg_referenz_SendungsId As Integer? = SafeInt(dr("chatMg_referenz_SendungsId"))
                                Dim chatMg_datetime As DateTime = If(IsDBNull(dr("chatMg_datetime")), DateTime.MinValue, Convert.ToDateTime(dr("chatMg_datetime")))
                                Dim chatMg_maName As String = If(IsDBNull(dr("chatMg_maName")), "", dr("chatMg_maName").ToString())
                                Dim chatMg_maFirma As String = If(IsDBNull(dr("chatMg_maFirma")), "", dr("chatMg_maFirma").ToString())
                                Dim chatMg_text As String = If(IsDBNull(dr("chatMg_text")), "", dr("chatMg_text").ToString())
                                Dim chatMg_referenz_KundenNr As String = If(IsDBNull(dr("chatMg_referenz_KundenNr")), "", dr("chatMg_referenz_KundenNr").ToString())

                                ' Message-Objekt direkt erstellen
                                Dim MSG As New cMessenger_ChatMessages(dr.Item("chatMg_id"), dr.Item("chatMg_chatId"), dr.Item("chatMg_maId"), dr.Item("chatMg_datetime"), dr.Item("chatMg_maName"), dr.Item("chatMg_maFirma"), dr.Item("chatMg_type"), dr.Item("chatMg_text"), IIf(IsDBNull(dr.Item("chatMg_anhang_docId")), Nothing, dr.Item("chatMg_anhang_docId")), IIf(IsDBNull(dr.Item("chatMg_referenz_AvisoId")), Nothing, dr.Item("chatMg_referenz_AvisoId")), IIf(IsDBNull(dr.Item("chatMg_referenz_SendungsId")), Nothing, dr.Item("chatMg_referenz_SendungsId")), dr.Item("chatMg_referenz_KundenNr"))

                                Me.CHAT_MESSAGES.Add(MSG)
                            End While
                        End Using
                    End Using
                End Using

                ' Nachrichten umdrehen, damit älteste zuerst angezeigt werden
                Me.CHAT_MESSAGES.Reverse()

            Catch ex As Exception
                MsgBox("Fehler in LOAD_MESSAGES: " & vbNewLine & ex.Message & vbNewLine & ex.StackTrace)
            End Try

        End Sub

        Private Function SafeInt(value As Object) As Integer?
            If IsDBNull(value) Then Return Nothing
            Dim s As String = value.ToString().Trim()
            Dim result As Integer
            If Integer.TryParse(s, result) Then
                Return result
            Else
                Return Nothing
            End If
        End Function

        Public Sub LOAD_MESSAGES_DATE(dateTmp As Date)
            Try
                Me.CHAT_MESSAGES.Clear()
                Using conn As SqlConnection = SQL.GetNewOpenConnectionADMIN()
                    Using cmd As New SqlCommand("SELECT chatMg_id,chatMg_chatId,chatMg_maId,chatMg_maName,chatMg_maFirma,chatMg_datetime,chatMg_type,chatMg_text,chatMg_anhang_docId,chatMg_referenz_AvisoId,chatMg_referenz_SendungsId,chatMg_referenz_KundenNr FROM [tblMessenger_ChatMessages] WHERE chatMg_chatId=@chat_id AND CAST(chatMg_datetime as date)>=@dateTmp order by chatMg_datetime asc", conn)
                        cmd.Parameters.AddWithValue("@chat_id", chat_id)
                        cmd.Parameters.AddWithValue("@dateTmp", dateTmp)
                        Dim dr = cmd.ExecuteReader()

                        While dr.Read

                            'Dim MSG As New cMessenger_ChatMessages(dr.Item("chatMg_id")) '----> 100 messages = 101 SQL calls
                            'Hier werden die einzelnen MSg-Obj nicht mehr per SQL geladen, sondern direkt als Objekt übergeben -> schneller!
                            Dim MSG As New cMessenger_ChatMessages(dr.Item("chatMg_id"), dr.Item("chatMg_chatId"), dr.Item("chatMg_maId"), dr.Item("chatMg_datetime"), dr.Item("chatMg_maName"), dr.Item("chatMg_maFirma"), dr.Item("chatMg_type"), dr.Item("chatMg_text"), IIf(IsDBNull(dr.Item("chatMg_anhang_docId")), Nothing, dr.Item("chatMg_anhang_docId")), IIf(IsDBNull(dr.Item("chatMg_referenz_AvisoId")), Nothing, dr.Item("chatMg_referenz_AvisoId")), IIf(IsDBNull(dr.Item("chatMg_referenz_SendungsId")), Nothing, dr.Item("chatMg_referenz_SendungsId")), dr.Item("chatMg_referenz_KundenNr")) 'Me.chat_id, dr.Item("chatMb_maId")) 'yxc
                            Me.CHAT_MESSAGES.Add(MSG)

                        End While

                        dr.Close()
                    End Using
                End Using
            Catch ex As Exception
                MsgBox("Fehler in der Funktion '" & System.Reflection.MethodInfo.GetCurrentMethod.Name & "'" & vbNewLine & vbNewLine & ex.Message & vbNewLine & vbNewLine & ex.StackTrace)
            End Try
        End Sub

        Public Function getUpdateCmd() As String
            Try
                Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()

                Dim str As String = ""
                For Each i In list
                    If Not i.isPrimaryParam Then
                        str &= "[" & i.Text & "] = @" & i.Scalarvariable & "," '.Replace("-", "").Replace(" ", "") & ","
                    End If
                Next
                str = str.Substring(0, str.Length - 1) 'wg. ','
                Return (" UPDATE [tblMessenger_Chat] SET " & str & " WHERE chat_id=@chat_id ")

            Catch ex As Exception
                MsgBox("Fehler in der Funktion '" & System.Reflection.MethodInfo.GetCurrentMethod.Name & "'" & vbNewLine & vbNewLine & ex.Message & vbNewLine & vbNewLine & ex.StackTrace)
            End Try
            Return ""
        End Function


        Public Function getInsertCmd() As String
            Try
                Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()
                Dim str As String = ""
                Dim values As String = ""
                For Each i In list
                    If Not i.isPrimaryParam Then
                        str &= "[" & i.Text & "],"
                        values &= "@" & i.Scalarvariable & "," '.Replace("-", "").Replace(" ", "") & ","
                    End If
                Next
                str = str.Substring(0, str.Length - 1) 'wg. ','
                values = values.Substring(0, values.Length - 1) 'wg. ','
                Return (" INSERT INTO tblMessenger_Chat  (" & str & ") VALUES(" & values & ")  ")
            Catch ex As Exception
                MsgBox("Fehler in der Funktion '" & System.Reflection.MethodInfo.GetCurrentMethod.Name & "'" & vbNewLine & vbNewLine & ex.Message & vbNewLine & vbNewLine & ex.StackTrace)
            End Try
            Return ""
        End Function


        Public Function DELETE() As Boolean 'obj As Object, tablename As String, where As String) As Boolean
            Dim sqlstr = " DELETE FROM [tblMessenger_Chat] WHERE chat_id=" & Me.chat_id
            Return SQL.doSQL(sqlstr, "ADMIN")
        End Function


        Public Function setOldChatsInactiv(olderthan As String) As Boolean

            Dim dateBack = If(olderthan <> "", CDate(Now.AddDays(olderthan * -1)), CDate(Now.AddDays(30 * -1)))
            Dim sqlstr = " Update [tblMessenger_Chat] set [chat_aktiv] = 0 from [tblMessenger_Chat] as chat WHERE chat.chat_aktiv = 1 and (chat.chat_id not in (select chatMg_chatId from [tblMessenger_ChatMessages] where chatMg_datetime >= '" & dateBack.ToShortDateString & "') and chat_erstelltAm <= '" & dateBack.ToShortDateString & "')  or (chat_erstelltAm <= '" & dateBack.ToShortDateString & "' and (select count(*) from [tblMessenger_ChatMessages] where chat_id = chatMg_chatId) = 0) and chat.chat_aktiv = 1"
            Return SQL.doSQL(sqlstr, "ADMIN")
        End Function


    End Class

    Public Class cMessenger_ChatMembers

        Property chatMb_chatId As Integer = -1
        Property chatMb_maId As Integer = -1
        Property chatMb_beitritt As Date = Now

        Dim SQL As New SQL


        Sub New(chatMb_chatId, chatMb_maId)
            Me.chatMb_chatId = chatMb_chatId
            Me.chatMb_maId = chatMb_maId
            Me.chatMb_beitritt = Now
        End Sub

        Public Function getParameterList() As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable)
            Dim list As New List(Of VERAG_PROG_ALLGEMEIN.SQLVariable)
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("chatMb_chatId", chatMb_chatId))

            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("chatMb_maId", chatMb_maId))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("chatMb_beitritt", chatMb_beitritt))

            Return list
        End Function



        Public Function SAVE() As Boolean
            Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()
            Dim sqlstr = " BEGIN TRAN If EXISTS(Select * FROM [tblMessenger_ChatMembers] WHERE chatMb_chatId=@chatMb_chatId And chatMb_maId=@chatMb_maId) " &
                       " BEGIN " & getUpdateCmd() & " End " &
                       " Else " &
                       " BEGIN " & getInsertCmd() & " End " &
                       " commit tran "

            Return SQL.doSQLVarList(sqlstr, "ADMIN", , list)
        End Function

        Public Sub LOAD()
            Try
                Using conn As SqlConnection = SQL.GetNewOpenConnectionADMIN()
                    Using cmd As New SqlCommand("Select * FROM [tblMessenger_ChatMembers] WHERE chatMb_chatId=@chatMb_chatId And chatMb_maId=@chatMb_maId ", conn)
                        cmd.Parameters.AddWithValue("@chatMb_chatId", chatMb_chatId)
                        cmd.Parameters.AddWithValue("@chatMb_maId", chatMb_maId)
                        Dim dr = cmd.ExecuteReader()
                        If dr.Read Then
                            For Each li In getParameterList()
                                Dim propInfo As PropertyInfo = Me.GetType.GetProperty(li.Scalarvariable)

                                If dr.Item(li.Text) Is DBNull.Value Then
                                    propInfo.SetValue(Me, Nothing)
                                Else
                                    propInfo.SetValue(Me, dr.Item(li.Text))
                                End If

                            Next

                        End If
                        dr.Close()
                    End Using
                End Using
            Catch ex As Exception
                MsgBox("Fehler In der Funktion '" & System.Reflection.MethodInfo.GetCurrentMethod.Name & "'" & vbNewLine & vbNewLine & ex.Message & vbNewLine & vbNewLine & ex.StackTrace)
            End Try
        End Sub


        Public Function getUpdateCmd() As String
            Try
                Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()

                Dim str As String = ""
                For Each i In list
                    If Not i.isPrimaryParam Then
                        str &= "[" & i.Text & "] = @" & i.Scalarvariable & "," '.Replace("-", "").Replace(" ", "") & ","
                    End If
                Next
                str = str.Substring(0, str.Length - 1) 'wg. ','
                Return (" UPDATE [tblMessenger_ChatMembers] SET " & str & " WHERE chatMb_chatId=@chatMb_chatId AND chatMb_maId=@chatMb_maId  ")

            Catch ex As Exception
                MsgBox("Fehler in der Funktion '" & System.Reflection.MethodInfo.GetCurrentMethod.Name & "'" & vbNewLine & vbNewLine & ex.Message & vbNewLine & vbNewLine & ex.StackTrace)
            End Try
            Return ""
        End Function


        Public Function getInsertCmd() As String
            Try
                Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()
                Dim str As String = ""
                Dim values As String = ""
                For Each i In list
                    If Not i.isPrimaryParam Then
                        str &= "[" & i.Text & "],"
                        values &= "@" & i.Scalarvariable & "," '.Replace("-", "").Replace(" ", "") & ","
                    End If
                Next
                str = str.Substring(0, str.Length - 1) 'wg. ','
                values = values.Substring(0, values.Length - 1) 'wg. ','
                Return (" INSERT INTO [tblMessenger_ChatMembers]  (" & str & ") VALUES(" & values & ")  ")
            Catch ex As Exception
                MsgBox("Fehler in der Funktion '" & System.Reflection.MethodInfo.GetCurrentMethod.Name & "'" & vbNewLine & vbNewLine & ex.Message & vbNewLine & vbNewLine & ex.StackTrace)
            End Try
            Return ""
        End Function


        Public Function DELETE([chatMb_maId]) As Boolean 'obj As Object, tablename As String, where As String) As Boolean
            Dim sqlstr = " DELETE FROM [tblMessenger_ChatMembers] WHERE [chatMb_chatId]=" & Me.[chatMb_chatId] & " AND [chatMb_maId] ='" & [chatMb_maId] & "'"
            Return SQL.doSQL(sqlstr, "ADMIN")
        End Function


    End Class

    Public Class cMessenger_ChatStatus

        Property chatMgSt_chatMsgId As Integer
        Property chatMgSt_MaId As Integer
        'Property chatMgSt_art As String = "STAT"
        Property chatMgSt_gelesen As Boolean = False
        Property chatMgSt_datetime As Date = Now

        Dim SQL As New SQL


        Sub New(chatMgSt_chatMsgId, chatMgSt_MaId, chatMgSt_gelesen)
            Me.chatMgSt_chatMsgId = chatMgSt_chatMsgId
            Me.chatMgSt_MaId = chatMgSt_MaId
            Me.chatMgSt_gelesen = chatMgSt_gelesen
            Me.chatMgSt_datetime = Now
        End Sub

        Public Function getParameterList() As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable)
            Dim list As New List(Of VERAG_PROG_ALLGEMEIN.SQLVariable)
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("chatMgSt_chatMsgId", chatMgSt_chatMsgId))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("chatMgSt_MaId", chatMgSt_MaId))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("chatMgSt_gelesen", chatMgSt_gelesen))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("chatMgSt_datetime", chatMgSt_datetime))

            Return list
        End Function



        Public Function SAVE() As Boolean
            Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()
            Dim sqlstr = " BEGIN TRAN IF EXISTS(SELECT * FROM tblMessenger_ChatMessages WHERE chatMgSt_chatMsgId=@chatMgSt_chatMsgId AND chatMgSt_MaId=@chatMgSt_MaId ) " &
                       " BEGIN " & getUpdateCmd() & " END " &
                       " Else " &
                       " BEGIN " & getInsertCmd() & " END " &
                       " commit tran "

            Return SQL.doSQLVarList(sqlstr, "ADMIN", , list)
        End Function

        Public Sub LOAD()
            Try
                Using conn As SqlConnection = SQL.GetNewOpenConnectionADMIN()
                    Using cmd As New SqlCommand("SELECT * FROM tblMessenger_ChatMessages WHERE chatMgSt_chatMsgId=@chatMgSt_chatMsgId AND chatMgSt_MaId=@chatMgSt_MaId  ", conn)
                        cmd.Parameters.AddWithValue("@chatMgSt_chatMsgId", chatMgSt_chatMsgId)
                        cmd.Parameters.AddWithValue("@chatMgSt_MaId", chatMgSt_MaId)
                        'cmd.Parameters.AddWithValue("@chatMgSt_art", chatMgSt_art)
                        Dim dr = cmd.ExecuteReader()
                        If dr.Read Then
                            For Each li In getParameterList()
                                Dim propInfo As PropertyInfo = Me.GetType.GetProperty(li.Scalarvariable)

                                If dr.Item(li.Text) Is DBNull.Value Then
                                    propInfo.SetValue(Me, Nothing)
                                Else
                                    propInfo.SetValue(Me, dr.Item(li.Text))
                                End If

                            Next

                        End If
                        dr.Close()
                    End Using
                End Using
            Catch ex As Exception
                MsgBox("Fehler in der Funktion '" & System.Reflection.MethodInfo.GetCurrentMethod.Name & "'" & vbNewLine & vbNewLine & ex.Message & vbNewLine & vbNewLine & ex.StackTrace)
            End Try
        End Sub


        Public Function getUpdateCmd() As String
            Try
                Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()

                Dim str As String = ""
                For Each i In list
                    If Not i.isPrimaryParam Then
                        str &= "[" & i.Text & "] = @" & i.Scalarvariable & "," '.Replace("-", "").Replace(" ", "") & ","
                    End If
                Next
                str = str.Substring(0, str.Length - 1) 'wg. ','
                Return (" UPDATE tblMessenger_ChatMessages SET " & str & " WHERE chatMgSt_chatMsgId=@chatMgSt_chatMsgId AND chatMgSt_MaId=@chatMgSt_MaId   ")

            Catch ex As Exception
                MsgBox("Fehler in der Funktion '" & System.Reflection.MethodInfo.GetCurrentMethod.Name & "'" & vbNewLine & vbNewLine & ex.Message & vbNewLine & vbNewLine & ex.StackTrace)
            End Try
            Return ""
        End Function


        Public Function getInsertCmd() As String
            Try
                Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()
                Dim str As String = ""
                Dim values As String = ""
                For Each i In list
                    If Not i.isPrimaryParam Then
                        str &= "[" & i.Text & "],"
                        values &= "@" & i.Scalarvariable & "," '.Replace("-", "").Replace(" ", "") & ","
                    End If
                Next
                str = str.Substring(0, str.Length - 1) 'wg. ','
                values = values.Substring(0, values.Length - 1) 'wg. ','
                Return (" INSERT INTO tblMessenger_ChatMessages  (" & str & ") VALUES(" & values & ")  ")
            Catch ex As Exception
                MsgBox("Fehler in der Funktion '" & System.Reflection.MethodInfo.GetCurrentMethod.Name & "'" & vbNewLine & vbNewLine & ex.Message & vbNewLine & vbNewLine & ex.StackTrace)
            End Try
            Return ""
        End Function


        Public Function DELETE([chatMgSt_MaId]) As Boolean 'obj As Object, tablename As String, where As String) As Boolean
            Dim sqlstr = " DELETE FROM tblMessenger_ChatMessages WHERE [chatMgSt_chatMsgId]=" & Me.chatMgSt_chatMsgId & " AND [chatMgSt_MaId] ='" & chatMgSt_MaId & "'"
            Return SQL.doSQL(sqlstr, "ADMIN")
        End Function


    End Class


    Public Class cMessenger_ChatMessages

        Property chatMg_id As Integer ' INT Not NULL PRIMARY KEY IDENTITY, 
        Property chatMg_chatId As Integer ' INT Not NULL,
        Property chatMg_maId As Integer ' INT Not NULL,
        Property chatMg_datetime As Date = Now
        Property chatMg_maName As String = VERAG_PROG_ALLGEMEIN.cAllgemein.MITARBEITER.Fullname
        Property chatMg_maFirma As String = VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA
        Property chatMg_type As String = "TEXT"
        Property chatMg_text As String = ""
        Property chatMg_anhang_docId As Integer ' int NULL,
        Property chatMg_referenz_AvisoId As Integer ' int NULL,
        Property chatMg_referenz_SendungsId As Integer ' int NULL,
        Property chatMg_referenz_KundenNr As Integer ' int NULL

        Public CHAT_MESSAGES_STATUS_LIST As New List(Of cMessenger_ChatMessageStatus)

        Dim SQL As New SQL


        Sub New(chatMg_id)
            Me.chatMg_id = chatMg_id
            LOAD()
        End Sub
        Sub New(chatMg_chatId, chatMg_maId)
            Me.chatMg_chatId = chatMg_chatId
            Me.chatMg_maId = chatMg_maId
        End Sub

        Sub New(chatMg_id, chatMg_chatId, chatMg_maId, chatMg_datetime, chatMg_maName, chatMg_maFirma, chatMg_type, chatMg_text, chatMg_anhang_docId, chatMg_referenz_AvisoId, chatMg_referenz_SendungsId, chatMg_referenz_KundenNr)
            Me.chatMg_id = chatMg_id
            Me.chatMg_chatId = chatMg_chatId
            Me.chatMg_maId = chatMg_maId
            Me.chatMg_datetime = chatMg_datetime
            Me.chatMg_maName = chatMg_maName
            Me.chatMg_maFirma = chatMg_maFirma
            Me.chatMg_type = chatMg_type
            Me.chatMg_text = chatMg_text
            Me.chatMg_anhang_docId = chatMg_anhang_docId
            Me.chatMg_referenz_AvisoId = chatMg_referenz_AvisoId
            Me.chatMg_referenz_SendungsId = chatMg_referenz_SendungsId
            Me.chatMg_referenz_KundenNr = chatMg_referenz_KundenNr
        End Sub

        Public Function getParameterList() As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable)
            Dim list As New List(Of VERAG_PROG_ALLGEMEIN.SQLVariable)
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("chatMg_id", chatMg_id,, True))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("chatMg_maId", chatMg_maId))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("chatMg_chatId", chatMg_chatId))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("chatMg_datetime", chatMg_datetime))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("chatMg_maName", chatMg_maName))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("chatMg_maFirma", chatMg_maFirma))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("chatMg_type", chatMg_type))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("chatMg_text", chatMg_text))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("chatMg_anhang_docId", chatMg_anhang_docId))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("chatMg_referenz_AvisoId", chatMg_referenz_AvisoId))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("chatMg_referenz_SendungsId", chatMg_referenz_SendungsId))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("chatMg_referenz_KundenNr", chatMg_referenz_KundenNr))

            Return list
        End Function



        Public Function SAVE(saveStat As Boolean, Optional CHAT_MEMBERS As List(Of cMessenger_ChatMembers) = Nothing) As Boolean
            Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()
            Dim sqlstr = " BEGIN TRAN IF EXISTS(SELECT * FROM tblMessenger_ChatMessages WHERE chatMg_id=@chatMg_id) " &
                       " BEGIN " & getUpdateCmd() & " END " &
                       " Else " &
                       " BEGIN " & getInsertCmd() & " END " &
                       " commit tran "
            Dim tmp_id = SQL.doSQLVarListID(Me.chatMg_id, sqlstr, "ADMIN", , list)
            If tmp_id > 0 Then
                Me.chatMg_id = tmp_id
                If saveStat Then SAVE_STATUS_FIRST(CHAT_MEMBERS)
                UPDATE_LASTMSG() ' Versucht einen TSTMP der letzten Nachricht einzutragen
                Return True
            Else
                Return False
            End If


            ''Return SQL.doSQLVarList(sqlstr, "ADMIN", , list)
        End Function


        Public Function UPDATE_LASTMSG() As Boolean
            Dim sqlstr = " UPDATE tblMessenger_Chat SET chat_lastMsg=getDate() WHERE [chat_id]=" & Me.chatMg_chatId & "  "
            Return SQL.doSQL(sqlstr, "ADMIN")
        End Function


        Public Sub LOAD()
            Try
                Using conn As SqlConnection = SQL.GetNewOpenConnectionADMIN()
                    Using cmd As New SqlCommand("SELECT * FROM tblMessenger_ChatMessages WHERE chatMg_id=@chatMg_id ", conn)
                        cmd.Parameters.AddWithValue("@chatMg_id", chatMg_id)
                        Dim dr = cmd.ExecuteReader()
                        If dr.Read Then
                            For Each li In getParameterList()
                                Dim propInfo As PropertyInfo = Me.GetType.GetProperty(li.Scalarvariable)

                                If dr.Item(li.Text) Is DBNull.Value Then
                                    propInfo.SetValue(Me, Nothing)
                                Else
                                    propInfo.SetValue(Me, dr.Item(li.Text))
                                End If

                            Next
                            LOAD_STATUS()
                        End If
                        dr.Close()
                    End Using
                End Using
            Catch ex As Exception
                MsgBox("Fehler in der Funktion '" & System.Reflection.MethodInfo.GetCurrentMethod.Name & "'" & vbNewLine & vbNewLine & ex.Message & vbNewLine & vbNewLine & ex.StackTrace)
            End Try
        End Sub


        Public Function getUpdateCmd() As String
            Try
                Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()

                Dim str As String = ""
                For Each i In list
                    If Not i.isPrimaryParam Then
                        str &= "[" & i.Text & "] = @" & i.Scalarvariable & "," '.Replace("-", "").Replace(" ", "") & ","
                    End If
                Next
                str = str.Substring(0, str.Length - 1) 'wg. ','
                Return (" UPDATE tblMessenger_ChatMessages SET " & str & " WHERE chatMg_id=@chatMg_id ")

            Catch ex As Exception
                MsgBox("Fehler in der Funktion '" & System.Reflection.MethodInfo.GetCurrentMethod.Name & "'" & vbNewLine & vbNewLine & ex.Message & vbNewLine & vbNewLine & ex.StackTrace)
            End Try
            Return ""
        End Function


        Public Function getInsertCmd() As String
            Try
                Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()
                Dim str As String = ""
                Dim values As String = ""
                For Each i In list
                    If Not i.isPrimaryParam Then
                        str &= "[" & i.Text & "],"
                        values &= "@" & i.Scalarvariable & "," '.Replace("-", "").Replace(" ", "") & ","
                    End If
                Next
                str = str.Substring(0, str.Length - 1) 'wg. ','
                values = values.Substring(0, values.Length - 1) 'wg. ','
                Return (" INSERT INTO tblMessenger_ChatMessages  (" & str & ") VALUES(" & values & ")  ")
            Catch ex As Exception
                MsgBox("Fehler in der Funktion '" & System.Reflection.MethodInfo.GetCurrentMethod.Name & "'" & vbNewLine & vbNewLine & ex.Message & vbNewLine & vbNewLine & ex.StackTrace)
            End Try
            Return ""
        End Function


        Public Function DELETE_MESSAGE() As Boolean
            chatMg_type = "DEL_" & chatMg_type
            Me.DELETE_STATUS() 'Alle Statuseinträge löschen
            Return SAVE(False)
        End Function

        Public Function DELETE([chatMgSt_MaId]) As Boolean 'obj As Object, tablename As String, where As String) As Boolean
            Dim sqlstr = " DELETE FROM tblMessenger_ChatMessages WHERE [chatMg_id]=" & Me.chatMg_id & "  "
            Return SQL.doSQL(sqlstr, "ADMIN")
        End Function

        Public Sub SAVE_STATUS_FIRST(CHAT_MEMBERS As List(Of cMessenger_ChatMembers))
            Try
                If CHAT_MEMBERS IsNot Nothing Then
                    For Each MB In CHAT_MEMBERS
                        Dim gelesen As Boolean = False
                        Dim gelesenDatetime = Nothing
                        Dim gelesenvon As Integer = -1
                        If MB.chatMb_maId > 0 AndAlso MB.chatMb_maId = VERAG_PROG_ALLGEMEIN.cAllgemein.USRID Then
                            gelesen = True
                            gelesenDatetime = Now()
                            gelesenvon = VERAG_PROG_ALLGEMEIN.cAllgemein.USRID
                        End If
                        Dim STAT As New cMessenger_ChatMessageStatus(Me.chatMg_id, MB.chatMb_maId, gelesen, gelesenDatetime, gelesenvon)
                        STAT.SAVE()
                    Next
                End If
            Catch ex As Exception
                MsgBox("Fehler in der Funktion '" & System.Reflection.MethodInfo.GetCurrentMethod.Name & "'" & vbNewLine & vbNewLine & ex.Message & vbNewLine & vbNewLine & ex.StackTrace)
            End Try
        End Sub

        'Public Function DELETE_STATUS() As Boolean 'obj As Object, tablename As String, where As String) As Boolean
        '    Dim sqlstr = " DELETE FROM [tblMessenger_ChatMessageStatus] WHERE chatMb_chatId=" & Me.chatMg_chatId
        '    Return SQL.doSQL(sqlstr, "ADMIN")
        'End Function

        Public Sub LOAD_STATUS()
            Try
                Me.CHAT_MESSAGES_STATUS_LIST.Clear()
                Using conn As SqlConnection = SQL.GetNewOpenConnectionADMIN()
                    Using cmd As New SqlCommand("SELECT chatMgSt_MaId FROM tblMessenger_ChatMessageStatus WHERE chatMgSt_chatMsgId=@chatMg_id  ", conn)
                        cmd.Parameters.AddWithValue("@chatMg_id", Me.chatMg_id)
                        Dim dr = cmd.ExecuteReader()
                        While dr.Read
                            Dim MB As New cMessenger_ChatMessageStatus(Me.chatMg_id, dr.Item("chatMgSt_MaId"))
                            Me.CHAT_MESSAGES_STATUS_LIST.Add(MB)
                        End While
                        dr.Close()
                    End Using
                End Using
            Catch ex As Exception
                MsgBox("Fehler in der Funktion '" & System.Reflection.MethodInfo.GetCurrentMethod.Name & "'" & vbNewLine & vbNewLine & ex.Message & vbNewLine & vbNewLine & ex.StackTrace)
            End Try
        End Sub

        Public Sub DELETE_STATUS()
            Try
                If SQL.doSQL("DELETE FROM tblMessenger_ChatMessageStatus WHERE chatMgSt_chatMsgId='" & Me.chatMg_id & "'", "ADMIN") Then
                    Me.CHAT_MESSAGES_STATUS_LIST.Clear()
                End If
            Catch ex As Exception
                MsgBox("Fehler in der Funktion '" & System.Reflection.MethodInfo.GetCurrentMethod.Name & "'" & vbNewLine & vbNewLine & ex.Message & vbNewLine & vbNewLine & ex.StackTrace)
            End Try
        End Sub
    End Class




    Public Class cMessenger_ChatMessageStatus

        Property chatMgSt_chatMsgId As Integer
        Property chatMgSt_MaId As Integer
        'Property chatMgSt_art As String = "STAT"
        Property chatMgSt_datetime As Date = Now
        Property chatMgSt_gelesen As Boolean = False
        Property chatMgSt_flag As Boolean = False
        Property chatMgSt_bestaetigt As Boolean = False
        Property chatMgSt_RM_Option As Object = Nothing
        Property chatMgSt_RM_Text As Object = Nothing
        Property chatMgSt_datetimeBestaetigt As Object = Nothing
        Property chatMgSt_datetimeGelesen As Object = Nothing
        Property chatMgSt_gelesenVonMaId As Integer

        Dim SQL As New SQL


        Sub New(chatMgSt_chatMsgId, chatMgSt_MaId)
            Me.chatMgSt_chatMsgId = chatMgSt_chatMsgId
            Me.chatMgSt_MaId = chatMgSt_MaId
            LOAD()
        End Sub

        Sub New(chatMgSt_chatMsgId, chatMgSt_MaId, chatMgSt_gelesen, chatMgSt_datetimeGelesen, chatMgSt_gelesenVonMaId, Optional chatMgSt_art = "STAT", Optional chatMgSt_flag = False, Optional chatMgSt_bestaetigt = Nothing)
            Me.chatMgSt_chatMsgId = chatMgSt_chatMsgId
            Me.chatMgSt_MaId = chatMgSt_MaId
            Me.chatMgSt_gelesen = chatMgSt_gelesen
            '  Me.chatMgSt_art = chatMgSt_art
            Me.chatMgSt_flag = chatMgSt_flag
            Me.chatMgSt_bestaetigt = chatMgSt_bestaetigt
            Me.chatMgSt_datetimeGelesen = IIf(chatMgSt_datetimeGelesen = Nothing, DBNull.Value, chatMgSt_datetimeGelesen)
            Me.chatMgSt_gelesenVonMaId = chatMgSt_gelesenVonMaId
        End Sub

        Sub New(chatMgSt_chatMsgId, chatMgSt_MaId, chatMgSt_gelesen, chatMgSt_bestaetigt, chatMgSt_RM_Option, chatMgSt_RM_Text)
            Me.chatMgSt_chatMsgId = chatMgSt_chatMsgId
            Me.chatMgSt_MaId = chatMgSt_MaId
            Me.chatMgSt_gelesen = chatMgSt_gelesen
            Me.chatMgSt_bestaetigt = chatMgSt_bestaetigt
            Me.chatMgSt_RM_Option = chatMgSt_RM_Option
            Me.chatMgSt_RM_Text = chatMgSt_RM_Text

        End Sub

        Public Function getParameterList() As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable)
            Dim list As New List(Of VERAG_PROG_ALLGEMEIN.SQLVariable)
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("chatMgSt_chatMsgId", chatMgSt_chatMsgId))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("chatMgSt_MaId", chatMgSt_MaId))
            ' list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("chatMgSt_art", chatMgSt_art))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("chatMgSt_datetime", chatMgSt_datetime))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("chatMgSt_flag", chatMgSt_flag))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("chatMgSt_gelesen", chatMgSt_gelesen))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("chatMgSt_bestaetigt", chatMgSt_bestaetigt))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("chatMgSt_RM_Option", chatMgSt_RM_Option))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("chatMgSt_RM_Text", chatMgSt_RM_Text))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("chatMgSt_datetimeBestaetigt", [chatMgSt_datetimeBestaetigt]))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("chatMgSt_datetimeGelesen", chatMgSt_datetimeGelesen))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("chatMgSt_gelesenVonMaId", chatMgSt_gelesenVonMaId))


            Return list
        End Function


        Public Shared Function STATUS_BESTAETIGEN(chatMgSt_chatMsgId, chatMgSt_bestaetigt, Optional chatMgSt_RM_Option = Nothing, Optional chatMgSt_RM_Text = Nothing) As Boolean
            Dim MGS_STAT As New cMessenger_ChatMessageStatus(chatMgSt_chatMsgId, VERAG_PROG_ALLGEMEIN.cAllgemein.USRID)
            MGS_STAT.chatMgSt_bestaetigt = chatMgSt_bestaetigt
            If chatMgSt_RM_Option IsNot Nothing Then MGS_STAT.chatMgSt_RM_Option = chatMgSt_RM_Option
            If chatMgSt_RM_Text IsNot Nothing Then MGS_STAT.chatMgSt_RM_Text = chatMgSt_RM_Text
            MGS_STAT.chatMgSt_datetimeBestaetigt = Now
            Return MGS_STAT.SAVE
        End Function

        Public Function SAVE() As Boolean
            Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()
            Dim sqlstr = " BEGIN TRAN IF EXISTS(SELECT chatMgSt_chatMsgId FROM tblMessenger_ChatMessageStatus WHERE chatMgSt_chatMsgId=@chatMgSt_chatMsgId AND chatMgSt_MaId=@chatMgSt_MaId ) " &
                       " BEGIN " & getUpdateCmd() & " END " &
                       " Else " &
                       " BEGIN " & getInsertCmd() & " END " &
                       " commit tran "

            Return SQL.doSQLVarList(sqlstr, "ADMIN", , list)
        End Function
        Public Function INSERT() As Boolean
            Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()

            MsgBox(getInsertCmd)
            Return SQL.doSQLVarList(getInsertCmd, "ADMIN", , list)
        End Function

        Public Sub LOAD()
            Try
                Using conn As SqlConnection = SQL.GetNewOpenConnectionADMIN()
                    Using cmd As New SqlCommand("SELECT * FROM tblMessenger_ChatMessageStatus WHERE chatMgSt_chatMsgId=@chatMgSt_chatMsgId AND chatMgSt_MaId=@chatMgSt_MaId  ", conn)
                        cmd.Parameters.AddWithValue("@chatMgSt_chatMsgId", chatMgSt_chatMsgId)
                        cmd.Parameters.AddWithValue("@chatMgSt_MaId", chatMgSt_MaId)
                        'cmd.Parameters.AddWithValue("@chatMgSt_art", chatMgSt_art)
                        Dim dr = cmd.ExecuteReader()
                        If dr.Read Then
                            For Each li In getParameterList()
                                Dim propInfo As PropertyInfo = Me.GetType.GetProperty(li.Scalarvariable)

                                If dr.Item(li.Text) Is DBNull.Value Then
                                    propInfo.SetValue(Me, Nothing)
                                Else
                                    propInfo.SetValue(Me, dr.Item(li.Text))
                                End If

                            Next

                        End If
                        dr.Close()
                    End Using
                End Using
            Catch ex As Exception
                MsgBox("Fehler in der Funktion '" & System.Reflection.MethodInfo.GetCurrentMethod.Name & "'" & vbNewLine & vbNewLine & ex.Message & vbNewLine & vbNewLine & ex.StackTrace)
            End Try
        End Sub


        Public Function getUpdateCmd() As String
            Try
                Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()

                Dim str As String = ""
                For Each i In list
                    If Not i.isPrimaryParam Then
                        str &= "[" & i.Text & "] = @" & i.Scalarvariable & "," '.Replace("-", "").Replace(" ", "") & ","
                    End If
                Next
                str = str.Substring(0, str.Length - 1) 'wg. ','
                Return (" UPDATE tblMessenger_ChatMessageStatus SET " & str & " WHERE chatMgSt_chatMsgId=@chatMgSt_chatMsgId AND chatMgSt_MaId=@chatMgSt_MaId ")

            Catch ex As Exception
                MsgBox("Fehler in der Funktion '" & System.Reflection.MethodInfo.GetCurrentMethod.Name & "'" & vbNewLine & vbNewLine & ex.Message & vbNewLine & vbNewLine & ex.StackTrace)
            End Try
            Return ""
        End Function


        Public Function getInsertCmd() As String
            Try
                Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()
                Dim str As String = ""
                Dim values As String = ""
                For Each i In list
                    If Not i.isPrimaryParam Then
                        str &= "[" & i.Text & "],"
                        values &= "@" & i.Scalarvariable & "," '.Replace("-", "").Replace(" ", "") & ","
                    End If
                Next
                str = str.Substring(0, str.Length - 1) 'wg. ','
                values = values.Substring(0, values.Length - 1) 'wg. ','
                Return (" INSERT INTO tblMessenger_ChatMessageStatus  (" & str & ") VALUES(" & values & ")  ")
            Catch ex As Exception
                MsgBox("Fehler in der Funktion '" & System.Reflection.MethodInfo.GetCurrentMethod.Name & "'" & vbNewLine & vbNewLine & ex.Message & vbNewLine & vbNewLine & ex.StackTrace)
            End Try
            Return ""
        End Function


        Public Function DELETE([chatMgSt_MaId]) As Boolean 'obj As Object, tablename As String, where As String) As Boolean
            Dim sqlstr = " DELETE FROM tblMessenger_ChatMessageStatus WHERE [chatMgSt_chatMsgId]=" & Me.chatMgSt_chatMsgId & " AND  [chatMgSt_MaId]=" & Me.chatMgSt_MaId & "  "
            Return SQL.doSQL(sqlstr, "ADMIN")
        End Function

    End Class

End Class
