Imports System.Globalization
Imports System.Net
Imports System.Threading
Imports DD_LIB_Standards
Imports DevExpress.LookAndFeel
Imports DevExpress.XtraBars
Imports DevExpress.XtraBars.Ribbon
Imports DevExpress.XtraBars.Ribbon.ViewInfo
Imports DevExpress.XtraNavBar

Public Class frmMain
    Dim strIPAddress As String

    Public Shared TIMER_SCAN As New System.Windows.Forms.Timer
    Public TIMER_INACTIVITY As ClassInactivity

    Public Sub OpenRibbon()
        ribbonMain.Minimized = False
    End Sub

    Public Sub CloseRibbon()
        ribbonMain.Minimized = True
    End Sub

    Private Shared Sub Scan_TickHandler(sender As Object, e As EventArgs)
        Try
            If ClassFolderWatcher.NEW_FILES = False Then Exit Sub
            ClassFolderWatcher.Check_Scan_Files()
            Dim open As Boolean = False
            If Not IsNothing(CURRENT_SCAN_TABLE) Then
                If CURRENT_SCAN_TABLE.Rows.Count > 0 Then
                    For Each form In My.Application.OpenForms
                        If (form.name = frmScanFiles.Name) Then
                            'form is loaded so can do work 
                            'if you need to check wether it is actually visible
                            If form.Visible Then
                                open = True
                                'do work when visible
                                If My.Settings.User_InBoxScan_NotinFront = False Then
                                    frmScanFiles.BringToFront()
                                End If
                            Else

                            End If
                        End If
                    Next
                    If open = False Then
                        Dim frm As New frmScanFiles
                        frm = frmScanFiles.Instance()
                        frm.Show()
                    End If
                End If
                If CURRENT_SCAN_TABLE.Rows.Count = 0 And open = True Then
                    frmScanFiles.Close()
                End If
                ClassFolderWatcher.NEW_FILES = False
            End If
        Catch ex As Exception
            MsgBox("Unexpected Error in Scan_TickHandler:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            TIMER_SCAN.Enabled = False
        End Try
    End Sub



    Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles Me.Load
        ' Referenz zu frmMain speichern
        MAIN_FORM = Me
        If ERROR_INIT <> "INVALID USER" Then
            Try
                ' Form Titel setzen
                ClassWindowLocation.LoadFormLocationSize(Me, 1, CURRENT_SCREEN_ID, "frmMain")
                Dim i = My.Application.UICulture.ToString()

                UserLookAndFeel.Default.SetSkinStyle(MyFormsDesign)


                ' GetIPv4Address()
                'Dim splash As New frmSplash()
                'splash.ShowDialog()

                ' MainForm Hintergrund laden
                SetBackgroundImage()

                Me.Text = Application.ProductName
                LabelVersion.Caption = String.Format("Version {0}", My.Application.Info.Version.ToString)
                StatusVersionDB.Caption = "DB-Version: " & DBVERSION
                LabelUser.Caption = USER_USERNAME

                'IP-Adresse-Auslesen
                Dim Addresslist() As IPAddress =
                Dns.GetHostEntry(Dns.GetHostName()).AddressList
                Dim IPs As IPAddress
                For Each IPs In Addresslist
                    'Aktuelle Machine
                    LOGGER.Info("" & My.Computer.Name & " - IP: " & IPs.ToString)
                    LabelMachine.Caption = My.Computer.Name & " - IP: " & IPs.ToString
                Next IPs


                LabelLanguage.Caption = "Language: " & USER_LANGUAGE
                Load_Connection_Dep_Data()

                Display_ConString

                'Wenn Argumente übergeben wurden, wird Formular geladen und zu record gesprungen
                ClassJumpRecord.ParseArgs()
                If Task_Popup_minutes <> 0 Then
                    TimerTasks.Interval = Task_Popup_minutes * 60000
                End If
                If USER_PERSONIFIED_TEST = True Then
                    StatusPersonifiedLogin.Visibility = BarItemVisibility.Always
                Else
                    StatusPersonifiedLogin.Visibility = BarItemVisibility.Never
                End If
                TimerInformation.Start()
            Catch ex As Exception
                MsgBox("Error in Load Form:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            End Try
            LOGGER.Debug("FormLoad finished!")
            Proxy_Server_Controls()
            CONN_Manager

        End If
    End Sub
    Sub CONN_Manager()
        Try
            RibbonPageGroupConnManager.Visible = False
            If Not IsNothing(CURRENT_TBPMO_CONN_SWITCH) Then
                If CURRENT_TBPMO_CONN_SWITCH.Rows.Count > 1 Then
                    Dim dt2 As DataTable = CURRENT_TBPMO_CONN_SWITCH
                    Dim dr2 As DataRow() = dt2.Select("ACTIVE = 0")
                    Dim name = ""

                    For Each row As DataRow In dr2
                        name = row.Item("DESCRIPTION")
                    Next
                    If name <> "" Then
                        BarButtonItemSwitchCon.Caption = "Switch Connection to: " & name
                        RibbonPageGroupConnManager.Visible = True
                    End If



                End If
            End If
        Catch ex As Exception
            LOGGER.Warn("Unexpected Error in CONN_Manager:" & ex.Message)
        End Try
    End Sub
    Sub Proxy_Server_Controls()
        Try
            If LICENSE_PROXY = True And clsDatabase.DB_PROXY_INITIALIZED = True Then
                'itemRefreshProxy.Visibility = BarItemVisibility.Always
                LabelProxyServer.Visibility = BarItemVisibility.Always
                LOGGER.Info("PROXY-SERVER is being used")
            Else
                'itemRefreshProxy.Visibility = BarItemVisibility.Never
                LabelProxyServer.Visibility = BarItemVisibility.Never
            End If
        Catch ex As Exception
            LOGGER.Warn("Unexpected Error in Sub Proxy_Server_Controls():" & ex.Message)
        End Try

    End Sub
    Public Sub RUN_TIMER()
        Try
            If TIMER_SCAN.Enabled = False And CURRENT_SCAN_FOLDERWATCH <> "" And FWSCAN_started = True Then
                If System.IO.Directory.Exists(CURRENT_SCAN_FOLDERWATCH) = False Then
                    LOGGER.Warn("SCAN PATH '" & CURRENT_SCAN_FOLDERWATCH & "'not accessable!")
                    Exit Sub
                End If
                TIMER_SCAN.Interval = 30000
                TIMER_SCAN.Enabled = True
                AddHandler TIMER_SCAN.Tick, AddressOf Scan_TickHandler
            Else
                If TIMER_SCAN.Enabled = True And CURRENT_SCAN_FOLDERWATCH <> "" And FWSCAN_started = True Then
                    TIMER_SCAN.Enabled = False

                    itemScanInbox.Visibility = BarItemVisibility.Always
                    RUN_TIMER()
                Else
                    TIMER_SCAN.Enabled = False
                End If
            End If
        Catch ex As Exception
            MsgBox("Unexpected Error in RUN_TIMER:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try

    End Sub
    Sub Load_Connection_Dep_Data()
        SetBackground()
        If ERROR_INIT = "NONE" Then
            If USER_IS_ADMIN = True Then
                pageAdmin.Visible = True
                ' itemRefreshProxy.Visibility = BarItemVisibility.Always
            Else
                'itemRefreshProxy.Visibility = BarItemVisibility.Never
            End If
            LoggedIn()

            'LoadMenuItems()
            LoadMenuItems2()
            LoadQuickStartItems()
        ElseIf ERROR_INIT = "DATABASE" Then
            Load_ConfigBasic()
        ElseIf ERROR_INIT = "INVALID USER" Then

        End If
        Load_TasksforUser()
    End Sub
    Sub LoggedIn()
        Try
            Dim oSQL = String.Format("SELECT COUNT(*) AS Expr1 FROM TBDD_USER_MODULE_LOG_IN WHERE UPPER(MODULE) = UPPER('Record-Organizer') AND CLIENT_ID = {0}", CLIENT_SELECTED)
            Dim anzahl = MYDB_ECM.GetScalarValue(oSQL)
            USERS_LOGGED_IN = CInt(anzahl)

        Catch ex As Exception

        End Try
        Dim msg = "Anzahl Angemeldete User: " & USERS_LOGGED_IN.ToString()
        If USER_LANGUAGE <> "de-DE" Then
            msg = "#User logged in: " & USERS_LOGGED_IN.ToString()
        End If
        LabelLoggedIn.Caption = msg
        LOGGER.Info(msg + "(+1)")
    End Sub
    Sub Display_ConString()
        Try
            Dim connection As New SqlClient.SqlConnection(MyConnectionString) 'csb.ConnectionString)
            Dim csb As New SqlClient.SqlConnectionStringBuilder
            csb.ConnectionString = MYDB_ECM.CurrentConnectionString
            Dim constr = connection.ConnectionString
            If constr.Contains("Trusted_Connection=True") = False Then
                constr = constr.Replace(csb.Password, "XXXXX")
            End If
            LabelConString.Caption = constr
        Catch ex As Exception
            MsgBox("Unexpected Error in Display_ConString:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Sub Load_TasksforUser()
        Try
            VWPMO_WF_ACTIVETableAdapter.Connection.ConnectionString = MYDB_ECM.CurrentConnectionString
            Me.VWPMO_WF_ACTIVETableAdapter.Fill(Me.DD_DMSDataSet.VWPMO_WF_ACTIVE, USER_LANGUAGE, USER_USERNAME)
            CURRENT_TASKS_GENERAL = Me.DD_DMSDataSet.VWPMO_WF_ACTIVE
        Catch ex As Exception
            MsgBox("Error in Load Tasks:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Private Sub frmMain_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
        If ERROR_INIT = "INVALID USER" Then
            Exit Sub
        End If
        If frmConstructor_Main.IsHandleCreated Then
            If INSERT_IN_ACTION = True Then
                Dim msg = "Bitte schliessen Sie zuerst das Hinzufügen des Datensatzes ab!"
                If USER_LANGUAGE <> "de-DE" Then
                    msg = "Please finish Your Adding-Procedure first!"
                End If
                MsgBox(msg, MsgBoxStyle.Information)
                e.Cancel = True
            End If
        End If

        Try
            ClassUser.LogoutUser()
            ClassWindowLocation.SaveFormLocationSize(Me, 1, CURRENT_SCREEN_ID, "frmMain")
            ToolStripManager.SaveSettings(Me)

            My.Settings.Save()

        Catch ex As Exception

        End Try
        'TempDateien löschen
        Try
            For Each _file In TEMP_FILES
                System.IO.File.Delete(_file)
            Next
        Catch ex As Exception

        End Try
    End Sub

    Private Shared Function LoadNoImage() As Bitmap
        Return Nothing
    End Function

    Private Shared Function LoadImage(path As Object)
        If Not IsDBNull(path) Then
            Dim filepath As String = DirectCast(path, String)
            filepath = CType(path, String)
            If System.IO.File.Exists(path) Then
                Return New Bitmap(filepath)
            Else
                Return LoadNoImage()
            End If
        Else
            Return LoadNoImage()
        End If
    End Function

    Public Sub LoadMenuItems2()
        Try
            Dim SQL2 As String = String.Format("SELECT A.GUID as CONSTRUCT_ID,A.NODE_NAVIGATION,B.FORM_ID, dbo.FNPMO_GETOBJECTCAPTION('{0}', 'CONSTR_MENUE' + CONVERT(VARCHAR(5), A.GUID), {1}) AS FORM_TITLE, A.SEQUENCE_MENU, A.ADDED_WHO, A.ADDED_WHEN, A.CHANGED_WHO," &
            "A.CHANGED_WHEN, A.MENU_IMG, A.SHORT_TITLE, A.LANGUAGE, " &
            "'CONSTR_MENUE' + CONVERT(VARCHAR(5), A.GUID) as OBECTNAME FROM TBPMO_FORM_CONSTRUCTOR A INNER JOIN TBPMO_FORM_CONSTRUCTOR_DETAIL B ON A.GUID = B.CONSTRUCT_ID where A.GUID in (SELECT CONSTRUCT_ID FROM TBPMO_CONSTRUCTOR_USER WHERE HOME_MENUE = 0 AND USER_ID = {2}) ORDER BY A.SEQUENCE_MENU", USER_LANGUAGE, CURRENT_SCREEN_ID, USER_GUID)
            Dim dt As DataTable = MYDB_ECM.GetDatatable(SQL2)

            If dt.Rows.Count <> 0 Then
                pageForms.Visible = True
                For Each oEntityRow As DataRow In dt.Rows
                    Dim image As Bitmap = Nothing

                    If IsDBNull(oEntityRow.Item("MENU_IMG")) Then
                        image = My.Resources.ResourceManager.GetObject("changechartlegendalignment_32x32")
                    Else
                        Dim bimg() As Byte = oEntityRow.Item("MENU_IMG")
                        Dim bitmap As Bitmap = ByteArrayToBitmap(bimg)
                        image = bitmap
                    End If

                    Dim title = oEntityRow.Item("FORM_TITLE")
                    If title = "CAPTION (OBJ) NOT TRANSLATED" Then
                        Dim objectname = oEntityRow.Item("OBECTNAME")
                        Dim objectname_temp = String.Format("Object {0} not translated", objectname)
                        Dim ins = String.Format("INSERT INTO TBPMO_LANGUAGE_OBJECT (LANGUAGE_TYPE,SCREEN_ID,PMO_OBJECT_NAME,CAPTION) VALUES " &
                                                "('{0}',{1},'{2}', '{3}')", USER_LANGUAGE, CURRENT_SCREEN_ID, objectname, objectname_temp)
                        If MYDB_ECM.ExecuteNonQuery(ins) = True Then
                            title = objectname_temp
                        End If
                    End If


                    Dim index As Integer = oEntityRow.Item("SEQUENCE_MENU")
                    Dim tag As String = oEntityRow.Item("CONSTRUCT_ID") & "#" & oEntityRow.Item("NODE_NAVIGATION") & "#" & oEntityRow.Item("FORM_ID")
                    Dim item As New BarButtonItem(ribbonMain.Manager, title)
                    item.RibbonStyle = RibbonItemStyles.Large
                    item.Caption = title
                    item.Tag = tag
                    item.Glyph = image
                    item.LargeGlyph = image

                    AddHandler item.ItemClick, AddressOf tbiOpenEntityFormClick
                    groupQuickAccessForm2.ItemLinks.Add(item)

                Next
            Else
                pageForms.Visible = False

            End If
        Catch ex As Exception
            MsgBox("Unexpected Error in Load QuickStart-Items:" & vbNewLine & ex.Message)
        End Try
    End Sub
    Public Sub LoadQuickStartItems()
        Try
            Dim SQL2 As String = String.Format("SELECT A.GUID as CONSTRUCT_ID, B.FORM_ID, A.NODE_NAVIGATION,dbo.FNPMO_GETOBJECTCAPTION('{0}', 'CONSTR_MENUE' + CONVERT(VARCHAR(5), A.GUID), {1}) AS FORM_TITLE, A.SEQUENCE_MENU, A.ADDED_WHO, A.ADDED_WHEN, A.CHANGED_WHO," &
            "A.CHANGED_WHEN, A.MENU_IMG, A.SHORT_TITLE, A.LANGUAGE, " &
            "'CONSTR_MENUE' + CONVERT(VARCHAR(5), A.GUID) as OBECTNAME FROM TBPMO_FORM_CONSTRUCTOR A INNER JOIN TBPMO_FORM_CONSTRUCTOR_DETAIL B On A.GUID = B.CONSTRUCT_ID where A.GUID in (SELECT CONSTRUCT_ID FROM TBPMO_CONSTRUCTOR_USER WHERE HOME_MENUE = 1 AND USER_ID = {2}) ORDER BY A.SEQUENCE_MENU", USER_LANGUAGE, CURRENT_SCREEN_ID, USER_GUID)
            Dim oDTConstructors As DataTable = MYDB_ECM.GetDatatable(SQL2)
            Dim image2 As Bitmap = LoadNoImage()

            Try
                If Not IsNothing(groupQuickAccessForm) Then
                    Do While 0 < groupQuickAccessForm.ItemLinks.Count
                        groupQuickAccessForm.ItemLinks.Remove(groupQuickAccessForm.ItemLinks(0))
                    Loop
                End If
            Catch ex As Exception

            End Try

            If oDTConstructors.Rows.Count <> 0 Then
                For Each row As DataRow In oDTConstructors.Rows
                    If Not IsDBNull(row.Item("MENU_IMG")) Then
                        Dim bimg() As Byte = row.Item("MENU_IMG")
                        Dim bitmap As Bitmap = ByteArrayToBitmap(bimg)
                        image2 = bitmap
                    Else
                        image2 = My.Resources.changechartlegendalignment_32x32
                    End If
                    Dim title = row.Item("FORM_TITLE")
                    If title = "CAPTION (OBJ) NOT TRANSLATED" Then
                        Dim objectname = row.Item("OBECTNAME")
                        Dim objectname_temp = String.Format("Object {0} not translated", objectname)
                        Dim ins = String.Format("INSERT INTO TBPMO_LANGUAGE_OBJECT (LANGUAGE_TYPE,SCREEN_ID,PMO_OBJECT_NAME,CAPTION) VALUES " &
                                                "('{0}',{1},'{2}', '{3}')", USER_LANGUAGE, CURRENT_SCREEN_ID, objectname, objectname_temp)
                        If MYDB_ECM.ExecuteNonQuery(ins) = True Then
                            title = objectname_temp
                        End If
                    End If


                    Dim index As Integer = row.Item("SEQUENCE_MENU")
                    Dim oTag As String = row.Item("CONSTRUCT_ID") & "#" & row.Item("NODE_NAVIGATION") & "#" & row.Item("FORM_ID")
                    Dim item As New BarButtonItem(ribbonMain.Manager, title)
                    item.RibbonStyle = RibbonItemStyles.Large
                    item.Caption = title
                    item.Tag = oTag
                    item.Glyph = image2

                    AddHandler item.ItemClick, AddressOf tbiOpenEntityFormClick
                    groupQuickAccessForm.ItemLinks.Add(item)

                    image2 = Nothing
                Next
            Else
                MsgBox("No consturctors configured for user!", MsgBoxStyle.Information)
                Clipboard.SetText(SQL2)
            End If

            Dim sql = "SELECT COUNT(GUID) FROM TBPMO_USER_GLOBAL_SEARCH WHERE USER_ID = " & USER_GUID
            Dim Count = MYDB_ECM.GetScalarValue(SQL)
            If Count = 0 Then
                btnGlobalSearch.Enabled = False
                groupSearchAllOver.Visible = False
            Else
                btnGlobalSearch.Enabled = True
                groupSearchAllOver.Visible = True
            End If
        Catch ex As Exception
            MsgBox("Unexpected Error in Load QuickStart-Items:" & vbNewLine & ex.Message)
        End Try

    End Sub
    Private Function Get_FormKonfig(ByVal oStr As String) As List(Of String)
        Return New List(Of String)(oStr.Split("#").ToArray())
    End Function
    Private Sub tbiOpenEntityFormClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs)
        Cursor = Cursors.WaitCursor
        Dim oArr As List(Of String) = Get_FormKonfig(e.Item.Tag)
        Dim formId As Integer = Integer.Parse(oArr(0))
        OpenFormConstructor(formId, oArr(1), oArr(2))
        Cursor = Cursors.Default
    End Sub

    Private Sub NavbarItem_Click(sender As Object, e As NavBarLinkEventArgs)

        Cursor = Cursors.WaitCursor
        Dim oArr As List(Of String) = Get_FormKonfig(e.Link.Item.Tag)
        Dim formId As Integer = Integer.Parse(oArr(0))
        OpenFormConstructor(formId, oArr(1), oArr(2))
        Cursor = Cursors.Default
    End Sub

    'Private Sub MenuItemClick(sender As Object, e As EventArgs)
    '    Dim item As ToolStripMenuItem = DirectCast(sender, ToolStripMenuItem)
    '    Dim formId As Integer = Integer.Parse(item.Tag)

    '    Cursor = Cursors.WaitCursor
    '    OpenFormInputFor(formId, 1)
    '    Cursor = Cursors.Default
    'End Sub
    Private Sub MenuItem2Click(sender As Object, e As EventArgs)
        Dim item As ToolStripMenuItem = DirectCast(sender, ToolStripMenuItem)
        Cursor = Cursors.WaitCursor
        Dim oArr As List(Of String) = Get_FormKonfig(item.Tag)
        Dim formId As Integer = Integer.Parse(oArr(0))
        OpenFormConstructor(formId, oArr(1), oArr(2))
        Cursor = Cursors.Default
    End Sub

    Private Sub QuickAccessClick(sender As Object, e As EventArgs)
        Dim btn As ToolStripButton = CType(sender, ToolStripButton)

        Dim oArr As List(Of String) = Get_FormKonfig(sender.Tag)
        Dim formId As Integer = Integer.Parse(oArr(0))
        OpenFormConstructor(formId, oArr(1), oArr(2))
    End Sub

    Private Sub SetBackground()
        Dim ctrl As Control
        Dim ctrlMDI As MdiClient

        For Each ctrl In Me.Controls
            Try
                ctrlMDI = CType(ctrl, MdiClient)
                ctrlMDI.BackColor = Me.BackColor
            Catch ex As Exception

            End Try
        Next
    End Sub

    Private Sub SetBackgroundImage()
        Try
            Dim SQL As String = "SELECT BACKGROUND_IMAGE FROM TBDD_MODULES WHERE NAME = 'Record-Organizer'"
            Dim bimage() As Byte = MYDB_ECM.GetScalarValue(SQL)

            If Not IsDBNull(bimage) Then

                Dim image As Bitmap = ByteArrayToBitmap(bimage)
                Me.BackgroundImage = image
                Me.BackgroundImageLayout = ImageLayout.Center

            End If
        Catch ex As Exception
            LOGGER.Warn("Unexpected Error in Load BackgroundImage: " & ex.Message)
        End Try

    End Sub

    Sub Refresh_TaskReminder()
        Load_TasksforUser()
        Try
            If DD_DMSDataSet.VWPMO_WF_ACTIVE.Rows.Count > 0 Then
                NotifyIcon.Visible = True
                If USER_LANGUAGE = "de-DE" Then
                    NotifyIcon.ShowBalloonTip(50000, "OrgFLOW-Unerledigte Tasks", "Sie haben unerledigte Tasks in Ihrem Verantwortungsbereich." & vbNewLine & "Bitte überprüfen Sie Ihre Workflow-Tasks", ToolTipIcon.Info)
                Else
                    NotifyIcon.ShowBalloonTip(50000, "OrgFLOW-Pending Tasks", "You have pending tasks in Your authority." & vbNewLine & "Please check Your Tasks", ToolTipIcon.Info)
                End If

            End If
        Catch ex As Exception
            MsgBox("Error in Refresh_TaskReminder:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Private Sub EbenenKonfiguratorToolStripMenuItem_Click(sender As Object, e As EventArgs)
        Cursor = Cursors.WaitCursor
        OpenFormOverview()
        Cursor = Cursors.Default
    End Sub
    Private Sub KalenderToolStripMenuItem_Click(sender As Object, e As EventArgs)
        Cursor = Cursors.WaitCursor
        OpenFormCalendar()
        Cursor = Cursors.Default
    End Sub

    Private Sub BeendenToolStripMenuItem_Click(sender As Object, e As EventArgs)
        Me.Close()
    End Sub



    Private Sub WorkflowTaskmanagementToolStripMenuItem_Click(sender As Object, e As EventArgs)
        OpenTaskmanagement()
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs)

    End Sub

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles TimerTasks.Tick
        Refresh_TaskReminder()

    End Sub

    Private Sub frmMain_Resize(sender As Object, e As EventArgs) Handles Me.Resize
        ' Repaint Form on Resize End
        Me.Invalidate(True)
        Me.Update()
    End Sub

    Private Sub frmMain_Shown(sender As Object, e As EventArgs) Handles Me.Shown
        Try
            Me.Cursor = Cursors.WaitCursor

            If ERROR_INIT <> "INVALID USER" Then

                If Task_Popup_minutes <> 0 Then
                    TimerTasks.Start()
                    Refresh_TaskReminder()
                End If

                RUN_TIMER()
                Timer5mins.Start()

                If Sett_ConstructorStart <> 0 Then
                    Cursor = Cursors.WaitCursor
                    OpenFormConstructor(Sett_ConstructorStart, False, 99)
                    Cursor = Cursors.Default
                End If

                'Lizenz abgellaufen, überprüfen ob User Admin ist
                If LICENSE_COUNT <= (USERS_LOGGED_IN + 1) Then
                    If USER_IS_ADMIN = True Then
                        LOGGER.Info("User is Admin - Timer will be started")
                        'If USER_LANGUAGE = "de-DE" Then
                        MsgBox("You now got 3 minutes for creating a new license", MsgBoxStyle.Information)
                        'Else
                        '    MsgBox("You now got 3 minutes to update the license!", MsgBoxStyle.Information)
                        'End If

                        'Timer starten
                        If TimerClose3Minutes.Enabled = False Then
                            TimerClose3Minutes.Start()
                        End If
                    End If
                Else
                    If LICENSE_SAP_Connect = True Then
                        Me.BarButtonItemSAPConnect.Enabled = True
                    End If
                End If
                Try
                    If ClassUpdate.Init = True And Not IsNothing(ClassUpdate.DT_UPDATE_ITEMS) Then
                        'MsgBox("532")
                        If Not IsNothing(ClassUpdate.DT_UPDATE) Then

                            If ClassUpdate.DT_UPDATE_ITEMS.Rows.Count > 0 Then
                                If ClassUpdate.InitUser = False Then
                                    Me.Cursor = Cursors.Default
                                    Exit Sub
                                Else
                                    If ClassUpdate.DT_USER_DATA.Rows.Count = 1 Or ClassUpdate.ALL_USERS = True Then
                                        If ClassUpdate.InitInstallPath() = False Then
                                            Exit Sub
                                        End If
                                    End If

                                    ClassUpdate.RUN_UPDATE()
                                    If ClassUpdate.UPDATE_ERROR = True Then
                                        Dim msg = String.Format("Während des Updatevorgangs für Version '{0}' haben sich unerwartet Fehler ereignet!" & vbNewLine & "Wollen Sie die Logdatei anzeigen?", ClassUpdate.VERSION_SERVER)
                                        If USER_LANGUAGE <> "de-DE" Then
                                            msg = String.Format("During update of version '{0}' unexpected errors occured!" & vbNewLine & "Would You like to show the logfile?", ClassUpdate.VERSION_SERVER)
                                        End If
                                        ClassHelper.InsertEssential_Log(USER_GUID, "USER-ID", String.Format("Unexpected errors occured during client-update update of version {0}!", ClassUpdate.VERSION_SERVER))
                                        Dim result As MsgBoxResult
                                        result = MessageBox.Show(msg, CAPTION_CONFIRMATION, MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                                        If result = MsgBoxResult.Yes Then
                                            Process.Start(LOGCONFIG.LogFile)
                                        End If
                                    Else
                                        If ClassUpdate.UPDATE_NECESSARY Then
                                            Dim msg = "Das Addon-Update war erfolgreich!"
                                            If USER_LANGUAGE <> "de-DE" Then
                                                msg = "The Addon-Update was successful!"
                                            End If
                                            MsgBox(msg, MsgBoxStyle.Information)
                                        End If


                                    End If
                                End If
                            End If
                        End If
                    End If
                Catch ex As Exception
                    MsgBox("Unexpected Error in Update VersionChecker: " & ex.Message, MsgBoxStyle.Critical)
                End Try

            Else
                MsgBox("Application will close now!", MsgBoxStyle.Critical)
                Me.Close()
            End If
            ' MsgBox("574")
            Dim myversion = CInt(My.Application.Info.Version.ToString.Replace(".", ""))
            Dim minreqver = CInt(MIN_REQUIRED_VERSION.Replace(".", ""))
            '   MsgBox("577")
            If myversion < minreqver Then
                MsgBox(String.Format("Your version '{0}' does not match the minimum required version and needs to be updated! Please contact Your systemadministrator!" & vbNewLine & "Application will close now.", My.Application.Info.Version.ToString), MsgBoxStyle.Exclamation)
                Me.Close()
            End If
            Try
                If USER_IS_ADMIN = False Or AUTO_LOGOUT_USER > 0 Then
                    TIMER_INACTIVITY = New ClassInactivity(AUTO_LOGOUT_USER)
                    Application.AddMessageFilter(New ClassInactivityFilter(Me))
                End If
            Catch ex As Exception
                ClassHelper.InsertEssential_Log(USER_GUID, "USER_ID", "Unexpected Error in AUOTP_LOGOUT_USER: " & ex.Message)
            End Try

        Catch ex As Exception
            MsgBox("Unexpected Error in FormShown: " & ex.Message, MsgBoxStyle.Critical)
        End Try




        'If DOCTYPE_COUNT_ACTUAL > LICENSE_DOCTYPE_COUNT Then
        '    If CURRENT_USER_IS_ADMIN = True Then
        '        Logger.Info("User is Admin - Timer will be started")
        '        If USER_LANGUAGE = "de-DE" Then
        '            MsgBox("Sie haben nun 3 Minuten Zeit eine neue Lizenz zu vergeben!", MsgBoxStyle.Information)
        '        Else
        '            MsgBox("You now got 3 minutes to update the license!", MsgBoxStyle.Information)
        '        End If

        '        'Timer starten
        '        If TimerClose3Minutes.Enabled = False Then
        '            TimerClose3Minutes.Start()
        '        End If
        '    End If
        'End If
        Me.Cursor = Cursors.Default

    End Sub
    Private Sub DokumentartkonfigurationToolStripMenuItem_Click(sender As Object, e As EventArgs)
        OpenDokumentartt()
    End Sub

    Private Sub MenuKonfigurationToolStripMenuItem_Click(sender As Object, e As EventArgs)
        OpenMenuDesigner()
    End Sub

    Private Sub UserKonfigurationToolStripMenuItem_Click(sender As Object, e As EventArgs)
        OpenUserKonfig()
    End Sub
    Private Sub ImageManagerToolStripMenuItem_Click(sender As Object, e As EventArgs)
        OpenImageManager()
    End Sub

    Private Sub tsQuickMenue_LocationChanged(sender As Object, e As EventArgs)
        'Console.WriteLine("locChanged" & tsQuickMenue.Location.ToString)
        'If tsQuickMenue.Location.ToString <> "{X=0,Y=0}" Then
        '    SaveMySettingsValue("tsQuickMenueLocation", tsQuickMenue.Location.ToString)
        'End If


    End Sub
    Private Sub GrundeinstellungenWindreamToolStripMenuItem_Click(sender As Object, e As EventArgs)
        OpenObjecttypeConfig()
    End Sub

    Private Sub MenuStrip1_ItemClicked(sender As Object, e As ToolStripItemClickedEventArgs)

    End Sub

    Private Sub GrundeinstellungenToolStripMenuItem_Click(sender As Object, e As EventArgs)
        frmRecOrgConfig_Basic.ShowDialog()
    End Sub

    Private Sub BarButtonItem1_ItemClick(sender As Object, e As ItemClickEventArgs) Handles BarButtonItem1.ItemClick
        OpenFormCalendar()
    End Sub

    Private Sub itemInfo_ItemClick(sender As Object, e As ItemClickEventArgs) Handles itemInfo.ItemClick
        Try
            Process.Start(MY_WIKISTRING)
        Catch ex As Exception
            MsgBox("No Help-Konfiguration. Please inform the system-Administrator", MsgBoxStyle.Exclamation)
        End Try
    End Sub

    Private Sub itemExit_ItemClick(sender As Object, e As ItemClickEventArgs) Handles itemExit.ItemClick
        Me.Close()
    End Sub

    Private Sub itemSettings_ItemClick(sender As Object, e As ItemClickEventArgs) Handles itemSettings.ItemClick
        Load_ConfigBasic()
    End Sub
    Private Sub itemRefreshProxy_ItemClick(sender As Object, e As ItemClickEventArgs)
        Me.Cursor = Cursors.WaitCursor
        Dim upd = "UPDATE TBPROXY_CONFIG SET SYNC_RUNNING = 1 WHERE GUID = 1"
        MYDB_ECM.ExecuteNonQuery(upd, True)
        If ClassProxy.Refresh_Object_Data() = True Then
            If ClassProxy.PRPROXY_SYNC_DOC_OBJECTS() = True Then
                Dim msg = "Die Proxydaten wurden erfolgreich synchronisiert!"
                If USER_LANGUAGE <> "de-DE" Then
                    msg = "All proxydata was refreshed successfully!"
                End If
                MessageBox.Show(msg, "", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Else
                MessageBox.Show("Error while refreshing proxy-data (Doc)!", "", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End If
        Else
            MessageBox.Show("Error while refreshing proxy-data (objects)!", "", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End If
        upd = "UPDATE TBPROXY_CONFIG SET SYNC_RUNNING = 0, LAST_SYNC = GETDATE() WHERE GUID = 1"
        MYDB_ECM.ExecuteNonQuery(upd, True)
        Me.Cursor = Cursors.Default
    End Sub
    Sub Load_ConfigBasic()
        frmConfig_Basic.ShowDialog()
        If CONNECTION_CHANGED = True Then
            ' Den User neu laden, damit MenuItems korrekt geladen werden können
            If ClassInit.InitDatabase = True Then

                ClassInit.InitUserLogin()
                Load_Connection_Dep_Data()
                Display_ConString()
            Else
                MsgBox("Unexpected Error when new Initialize Database!", MsgBoxStyle.Critical)
            End If


        End If
        If Task_Popup_minutes <> 0 Then
            TimerTasks.Stop()
            TimerTasks.Interval = Task_Popup_minutes * 60000
            TimerTasks.Start()
        Else
            TimerTasks.Enabled = False
            TimerTasks.Stop()
        End If
        Proxy_Server_Controls()
        RUN_TIMER()

    End Sub
    Private Sub BarButtonItem3_ItemClick(sender As Object, e As ItemClickEventArgs) Handles BarButtonItem3.ItemClick
        Cursor = Cursors.WaitCursor
        OpenFormOverview()
        Cursor = Cursors.Default
    End Sub

    Private Sub BarButtonItem4_ItemClick(sender As Object, e As ItemClickEventArgs) Handles BarButtonItem4.ItemClick
        OpenTaskmanagement()
    End Sub

    Private Sub BarButtonItem5_ItemClick(sender As Object, e As ItemClickEventArgs) Handles BarButtonItem5.ItemClick
        OpenUserKonfig()
    End Sub

    Private Sub BarButtonItem6_ItemClick(sender As Object, e As ItemClickEventArgs) Handles BarButtonItem6.ItemClick
        OpenMenuDesigner()
    End Sub

    Private Sub BarButtonItem7_ItemClick(sender As Object, e As ItemClickEventArgs) Handles BarButtonItem7.ItemClick
        OpenImageManager()
    End Sub
    Private Sub BarButtonItem2_ItemClick(sender As Object, e As ItemClickEventArgs) Handles BarButtonItem2.ItemClick
        frmRecOrgConfig_Basic.ShowDialog()
    End Sub

    Private Sub BarButtonItem10_ItemClick(sender As Object, e As ItemClickEventArgs) Handles BarButtonItem10.ItemClick
        Load_ConfigBasic()
    End Sub

    Private Sub BarButtonItem12_ItemClick(sender As Object, e As ItemClickEventArgs) Handles BarButtonItem12.ItemClick
        OpenWiedervorlage()
    End Sub
    Private Sub BarButtonItem14_ItemClick(sender As Object, e As ItemClickEventArgs) Handles BarButtonItemConnections.ItemClick
        Dim frm As New frmConnections
        frm.MdiParent = Me
        frm.Show()
    End Sub

    Private Sub BarButtonItem16_ItemClick(sender As Object, e As ItemClickEventArgs) Handles BarButtonItem16.ItemClick
        Close_Maximized_Forms()
        Dim frm As New frmConstructorDesigner
        frm.MdiParent = Me
        frm.Show()
    End Sub

    Private Sub BarButtonItem17_ItemClick(sender As Object, e As ItemClickEventArgs) Handles BarButtonItem17.ItemClick
        OpenTemplatemanagement()
    End Sub

    Private Sub TimerClose3Minutes_Tick(sender As Object, e As EventArgs) Handles TimerClose3Minutes.Tick
        If LICENSE_EXPIRED = True Or LICENSE_COUNT <= (USERS_LOGGED_IN + 1) Then
            'If USER_LANGUAGE = "de-DE" Then
            '    MsgBox("Global Indexer wird nun geschlossen, weil keine neue Lizenzdaten eingegeben wurden!", MsgBoxStyle.Information)
            'Else
            MsgBox("Record Organizer will now be closed, cause no new license was updated!", MsgBoxStyle.Information)
            'End If
            Me.Close()
        Else
            TimerClose3Minutes.Stop()
        End If
    End Sub

    Private Sub frmMain_KeyUp(sender As Object, e As KeyEventArgs) Handles MyBase.KeyUp
        Select Case e.KeyCode
            Case Keys.F12
                Try
                    frmLicense.ShowDialog()
                Catch ex As Exception

                End Try
        End Select
    End Sub

    Private Sub BarButtonItem18_ItemClick(sender As Object, e As ItemClickEventArgs) Handles BarButtonItem18.ItemClick
        Close_Maximized_Forms()
        Dim frm As New frmLanguage_Translator
        frm.MdiParent = Me
        frm.Show()
    End Sub

    Public Sub New()
        Dim splash As New frmSplash()
        splash.ShowDialog()
        Try
            If ERROR_INIT <> "INVALID USER" Then
                Dim cultureInfo As System.Globalization.CultureInfo
                cultureInfo = New System.Globalization.CultureInfo(USER_LANGUAGE)
                cultureInfo.DateTimeFormat.ShortDatePattern = USER_DATE_FORMAT
                Thread.CurrentThread.CurrentCulture = cultureInfo
                Thread.CurrentThread.CurrentUICulture = cultureInfo
                CultureInfo.DefaultThreadCurrentCulture = cultureInfo
                CultureInfo.DefaultThreadCurrentUICulture = cultureInfo
            End If
        Catch ex As Exception

        End Try


        ' Dieser Aufruf ist für den Designer erforderlich.
        InitializeComponent()

        ' Fügen Sie Initialisierungen nach dem InitializeComponent()-Aufruf hinzu.

    End Sub

    Private Sub NotifyIcon_BalloonTipClicked(sender As Object, e As EventArgs) Handles NotifyIcon.BalloonTipClicked
        OpenFormCockpit()
    End Sub
    Private Sub CockpitAnzeigenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles CockpitAnzeigenToolStripMenuItem.Click
        OpenFormCockpit()
    End Sub

    Private Sub BarButtonItem20_ItemClick(sender As Object, e As ItemClickEventArgs) Handles BarButtonItem20.ItemClick
        Close_Maximized_Forms()
        Dim frm As New frmRight_Management
        frm = frmRight_Management.Instance()
        frm.MdiParent = MAIN_FORM
        frm.Show()
    End Sub

    Private Sub BarButtonItem21_ItemClick(sender As Object, e As ItemClickEventArgs) Handles BarButtonItemSAPConnect.ItemClick
        Dim frm As New frmSAP_FuBa
        frm.MdiParent = Me
        frm.Show()
    End Sub

    Private Sub Button1_Click_1(sender As Object, e As EventArgs)

    End Sub
    Private Sub BarButtonItemStructureNOdes_ItemClick(sender As Object, e As ItemClickEventArgs) Handles BarButtonItemStructureNOdes.ItemClick
        Close_Maximized_Forms()
        Dim frm As New frmStructureNodeConfig
        frm = frmStructureNodeConfig.Instance()
        frm.MdiParent = MAIN_FORM
        frm.Show()
    End Sub

    Private Sub BarButtonItem14_ItemClick_1(sender As Object, e As ItemClickEventArgs) Handles BarButtonItem14.ItemClick
        Close_Maximized_Forms()
        OpenDokumentartt()
    End Sub

    Private Sub BarButtonItem21_ItemClick_1(sender As Object, e As ItemClickEventArgs) Handles BarButtonItem21.ItemClick
        Close_Maximized_Forms()
        OpenObjecttypeConfig()
    End Sub

    Private Sub BarButtonItem22_ItemClick(sender As Object, e As ItemClickEventArgs) Handles BarButtonItem22.ItemClick
        Close_Maximized_Forms()
        OpenWindream_Files()
    End Sub

    Private Sub BarButtonItem8_ItemClick(sender As Object, e As ItemClickEventArgs) Handles BarButtonItem8.ItemClick
        Close_Maximized_Forms()
        OpenRightsmanager()
    End Sub

    Private Sub BarButtonItem9_ItemClick(sender As Object, e As ItemClickEventArgs) Handles BarButtonItem9.ItemClick
        Dim frm As New frmWM_Resultlist_Config()
        frm.MdiParent = MAIN_FORM
        frm.Show()
    End Sub

    Private Sub ribbonMain_Merge(sender As Object, e As RibbonMergeEventArgs) Handles ribbonMain.Merge
        ' Zeigt im Ribbon Control den Kalender-Tab an, wenn der Kalender Maximiert wurde
        Dim oMergeableRibbons = New List(Of String) From {"ribbonCalendar", "ribbonNodeNavigation"}
        Dim oMergedRibbonControl = e.MergedChild

        If oMergeableRibbons.Contains(oMergedRibbonControl.Name) Then
            Dim oMergedPage = e.MergeOwner.MergedPages.First()
            e.MergeOwner.SelectedPage = oMergedPage
        End If
    End Sub

    Private Sub itemAbout_ItemClick(sender As Object, e As ItemClickEventArgs) Handles itemAbout.ItemClick
        frmAbout.ShowDialog()
    End Sub

    Private Sub BarButtonItem19_ItemClick(sender As Object, e As ItemClickEventArgs) Handles BarButtonItem19.ItemClick
        frmLicense_User.ShowDialog()
    End Sub

    Private Sub frmMain_MdiChildActivate(sender As Object, e As EventArgs) Handles Me.MdiChildActivate
        Dim mainForm As Form = sender
        Dim constructorFound = False

        For Each childForm As Form In mainForm.MdiChildren
            If (childForm.Name = "frmConstructor_Main") Then
                Dim form As frmConstructor_Main = childForm
                Dim formOpening = Not (form.Disposing Or form.IsDisposed)

                ' Wird das Child Formular gerade geöffnet?
                If formOpening Then
                    constructorFound = True
                End If
            End If
        Next

        ' Wenn gerade ein frmConstructor_Main geöffnet wurde, 
        ' wird ribbonMain minimiert
        If constructorFound Then
            ribbonMain.Minimized = True
        Else
            ribbonMain.Minimized = False
        End If
    End Sub

    Private Sub ribbonMain_MouseMove(sender As Object, e As MouseEventArgs) Handles ribbonMain.MouseMove
        Dim hitInfo As RibbonHitInfo = ribbonMain.CalcHitInfo(e.Location)

        ' Wenn ribbonMain minimiert ist und die Maus über den Reitern
        If (ribbonMain.Minimized And hitInfo.HitTest = RibbonHitTest.PageHeader) Then
            ribbonMain.Minimized = False
        End If
    End Sub

    Private Sub BarButtonItem23_ItemClick(sender As Object, e As ItemClickEventArgs) Handles btnGlobalSearch.ItemClick
        OpenSearchAllOVer()

    End Sub
    Private Sub BarButtonItem25_ItemClick(sender As Object, e As ItemClickEventArgs) Handles bbtnItemViewsUser.ItemClick
        OpenViewsUser()
    End Sub

    Private Sub BarButtonItem25_ItemClick_1(sender As Object, e As ItemClickEventArgs) Handles BarButtonItem25.ItemClick
        OpenStatisticsADDI()
    End Sub

    Private Sub TimerInforamtion_Tick(sender As Object, e As EventArgs) Handles TimerInformation.Tick
        If CURRENT_NOTIFICATION_MSG <> String.Empty Then
            Dim caption = "Information Dateiimport"
            If USER_LANGUAGE <> "de-DE" Then
                caption = "Information File-Import"
            End If
            NotifyIcon.ShowBalloonTip(30000, caption, CURRENT_NOTIFICATION_MSG, ToolTipIcon.Info)
            CURRENT_NOTIFICATION_MSG = ""
        End If
    End Sub

    Private Sub BarButtonItem13_ItemClick(sender As Object, e As ItemClickEventArgs) Handles BarButtonItem13.ItemClick
        OpenLogRecord()
    End Sub

    Private Sub BarButtonItemSwitchCon_ItemClick(sender As Object, e As ItemClickEventArgs) Handles BarButtonItemSwitchCon.ItemClick
        Try
            Dim dt2 As DataTable = CURRENT_TBPMO_CONN_SWITCH
            Dim drActive As DataRow() = dt2.Select("ACTIVE = 1")
            Dim drInActive As DataRow() = dt2.Select("ACTIVE = 0")
            Dim oSQLDescription = ""
            Dim oSqlcon = ""
            Dim oSqlcon_Proxy = ""
            Dim oWM_ALIAS = ""
            Dim oINACTIVE_GUID
            Dim oACTIVE_GUID
            For Each row As DataRow In drInActive
                oINACTIVE_GUID = row.Item("GUID")
                oSQLDescription = row.Item("DESCRIPTION")
                oSqlcon = row.Item("SQL_CONNECTION")
                oSqlcon_Proxy = row.Item("SQL_CONNECTION_PROXY")
                oWM_ALIAS = row.Item("WM_ALIAS")
            Next
            For Each row As DataRow In drActive
                oACTIVE_GUID = row.Item("GUID")
            Next


            If oSQLDescription <> "" Then
                Dim oresult As MsgBoxResult
                Dim msg = "Wollen Sie die Verbindungs-Konfiguration nun auf '" & oSQLDescription & "' ändern?"
                If USER_LANGUAGE <> "de-DE" Then
                    msg = "Would You like to change the Connection-configuration to '" & oSQLDescription & "'?"
                End If
                oresult = MessageBox.Show(msg, CAPTION_CONFIRMATION, MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                If oresult = MsgBoxResult.Yes Then
                    BarButtonItemSwitchCon.Caption = "Switch Connection to: " & oSQLDescription
                    Try
                        My.Computer.Registry.SetValue("HKEY_CURRENT_USER\Software\A.I.S. GmbH\windream\3.6\ServerShareSelector", "CurrentAlias", oWM_ALIAS)
                        My.Computer.Registry.SetValue("HKEY_CURRENT_USER\Software\A.I.S. GmbH\windream\3.6\ServerShareSelector", "VFSAlias", oWM_ALIAS)
                    Catch ex As Exception
                        LOGGER.Warn("Unexpected error in Changing WMAlias: " & ex.Message)
                        MsgBox("Unexpected error in Changing WMAlias: " & ex.Message, MsgBoxStyle.Critical)
                        Exit Sub
                    End Try
                    Try
                        Dim IndexService = CreateObject("WMIndexServer.WMIdxSvControl")
                        IndexService.shutdown
                        IndexService.Start
                    Catch ex As Exception
                        LOGGER.Warn("Unexpected error in Restarting IndexService: " & ex.Message)
                        MsgBox("Unexpected error in Restarting IndexService: " & ex.Message, MsgBoxStyle.Critical)
                        Exit Sub
                    End Try
                    Try
                        Dim ControlCenter = CreateObject("Wmcc.ControlCenter")
                        ControlCenter.StartVFSService(0)
                        ControlCenter.StartVFSService(1)
                    Catch ex As Exception
                        LOGGER.Warn("Unexpected error in Restarting ControlCenter: " & ex.Message)
                        MsgBox("Unexpected error in Restarting ControlCenter: " & ex.Message, MsgBoxStyle.Critical)
                        Exit Sub
                    End Try

                    SaveMySettingsValue("MyConnectionString", oSqlcon, "ConfigMain")
                    MyConnectionString = oSqlcon
                    Display_ConString()

                    If oSqlcon_Proxy <> String.Empty Then
                        SaveMySettingsValue("MyProxyConnectionString", oSqlcon_Proxy, "ConfigMain")
                        ClassProxy.MyPROXYConnectionString = oSqlcon_Proxy
                    End If
                    Dim sql = String.Format("UPDATE TBPMO_CLIENT_CONN_SWITCH_USER SET ACTIVE = 1 WHERE GUID = {0}", oINACTIVE_GUID)
                    MYDB_ECM.GetScalarValue(SQL)
                    If ClassInit.InitDatabase = True Then
                        ClassInit.InitUserLogin()
                        Load_Connection_Dep_Data()

                        sql = String.Format("UPDATE TBPMO_CLIENT_CONN_SWITCH_USER SET ACTIVE = 1 WHERE UPPER(CONN_NAME) = UPPER('{0}') AND USER_ID = {1}", oSQLDescription, USER_GUID)
                        Dim oSuccess As Boolean = False
                        If MYDB_ECM.ExecuteNonQuery(Sql) = True Then
                            oSuccess = True
                        End If
                        If oSuccess = True Then
                            msg = "Die Client-Verbindung wurde erfolgreich gewechselt!"
                            If USER_LANGUAGE <> "de-DE" Then
                                msg = "The Client-Connection was changed successfully!"
                            End If
                            MsgBox(msg, MsgBoxStyle.Information)
                        Else
                            msg = "Die Client-Verbindung konnte nicht erfolgreich gewechselt werden!"
                            If USER_LANGUAGE <> "de-DE" Then
                                msg = "The Client-Connection could not be changed!"
                            End If
                            MsgBox(msg, MsgBoxStyle.Critical)
                        End If



                        ClassInit.Init_CONN_SWITCH()
                        CONN_Manager()
                    End If
                End If

            End If
        Catch ex As Exception
            MsgBox("Unexpected error in BarButtonItemSwitchCon.ItemClick: " & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub Timer5mins_Tick(sender As Object, e As EventArgs) Handles Timer5mins.Tick
        LoggedIn()
    End Sub
End Class
