Imports System.Net
Imports System.Net.Mail
Imports System.Drawing
Imports System.Configuration
Imports System.Data.SqlClient
Imports System.Data
Imports System.Threading
Imports System.Threading.Tasks
Imports System.Security.Cryptography

Partial Class ForgotPW
    Inherits System.Web.UI.Page
    Dim ConnectionString As String = String.Empty
    Dim salt As Byte()
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        If Page.IsPostBack = True Then
            Page.MaintainScrollPositionOnPostBack = True
            VERAG_VARIABLES.initerrorcount()
            salt = VERAG_VARIABLES.GenerateSalt(RandomInteger(Math.Pow(2, 3), Math.Pow(2, 10)))
        Else
            Page.MaintainScrollPositionOnPostBack = False
            VERAG_VARIABLES.initerrorcount()
        End If
    End Sub
    Protected Sub btn_Back_Click(sender As Object, e As EventArgs)
        Response.Redirect("login_FLEX.aspx")
    End Sub


    Protected Async Sub btn_Send_Click(sender As Object, e As EventArgs)
        Try
            Dim username As String = String.Empty
            Dim password As String = String.Empty
            Dim email As String = String.Empty
            Dim tokenname As String = String.Empty
            Dim customerID As String = String.Empty
            Dim isusrnmright As Boolean = False
            Dim isCustomeridright As Boolean = False
            Dim isemailright As Boolean = False
            Dim UserID As String = String.Empty
            CustomerIDrequired.Validate()
            valreqtxtusername.Validate()
            valreqtxtEmail.Validate()
            If String.IsNullOrEmpty(txtEmail.Text) = False And String.IsNullOrEmpty(txt_Username.Text) = False And String.IsNullOrEmpty(txt_CustomerID.Text) = False And String.IsNullOrEmpty(txtEmail_M.Text) = True And String.IsNullOrEmpty(txt_Username_M.Text) = True And String.IsNullOrEmpty(txt_CustomerID_M.Text) = True Then
                valreqtxtusername.Enabled = True
                valreqtxtEmail.Enabled = True
                regexval_txt_Email_2.Enabled = True
                regexval_txt_Email.Enabled = True
                check_UserName_regex.Enabled = True
                CustomerIDrequired.Enabled = True
                valid_getNumberInput.Enabled = True

                regexval_2_txt_Email_M.Enabled = False
                regexval_txt_Email_M.Enabled = False
                valreqtxtEmail_M.Enabled = False
                valreqtxtusername_M.Enabled = False
                check_UserName_regex_M.Enabled = False
                CustomerID_M_required.Enabled = False
                valid_getNumber_M_Input.Enabled = False

                valreqtxtEmail.Validate()
                If valreqtxtEmail.IsValid = True Then
                    regexval_txt_Email.Validate()
                    If regexval_txt_Email.IsValid = False Then
                        regexval_txt_Email.ForeColor = Drawing.Color.OrangeRed
                        VERAG_VARIABLES.seterrorcount(2)
                        regexval_txt_Email.ErrorMessage = VERAG_VARIABLES.geterrornumb + "Annotation: The Domain is not valid!"
                        regexval_txt_Email_2.Validate()
                        If regexval_txt_Email_2.IsValid = True Then
                            email = txtEmail.Text
                            lblMessage.ForeColor = Drawing.Color.Green
                            lblMessage.Text = "E-mail Adresse is valid.."
                        End If
                    Else
                        regexval_txt_Email.Validate()
                        If regexval_txt_Email.IsValid = True Then
                            lblMessage.ForeColor = Drawing.Color.Green
                            lblMessage.Text = "E-mail Address is correct."
                            email = txtEmail.Text
                        End If
                    End If
                End If

                CustomerIDrequired.Validate()
                If CustomerIDrequired.IsValid = True Then
                    valid_getNumberInput.Validate()
                    If valid_getNumberInput.IsValid = True Then
                        customerID = txt_CustomerID.Text
                    Else
                        valid_getNumberInput.ForeColor = Drawing.Color.Red
                        VERAG_VARIABLES.seterrorcount(2)
                        valid_getNumberInput.ErrorMessage = VERAG_VARIABLES.geterrornumb + "The Customer-ID is not numeric or too long."
                    End If
                End If

                valreqtxtusername.Validate()
                If valreqtxtusername.IsValid = True Then
                    check_UserName_regex.Validate()
                    If check_UserName_regex.IsValid = False Then
                        check_UserName_regex.ForeColor = Drawing.Color.Red
                        VERAG_VARIABLES.seterrorcount(3)
                        check_UserName_regex.ErrorMessage = VERAG_VARIABLES.geterrornumb + "Username is too long."
                        isusrnmright = False
                    Else
                        username = txt_Username.Text
                        isusrnmright = True
                        check_UserName_regex.ForeColor = Drawing.Color.Green
                        check_UserName_regex.ErrorMessage = "Username is not right."
                    End If
                End If
            Else
                'MsgBox("The form has not been filled completeley.", MsgBoxStyle.Critical, "Error08")
                lblMessage.ForeColor = Color.Red
                VERAG_VARIABLES.seterrorcount(8)
                lblMessage.Text = VERAG_VARIABLES.geterrornumb + "This Form has to be filled out completely."
            End If

            'Erweiterte Degub Msg-Box
            'MsgBox("Userdaten in App" + Environment.NewLine + email + Environment.NewLine + username + Environment.NewLine + "Userdaten desktop" + txt_Username.Text + Environment.NewLine + txtEmail.Text + Environment.NewLine + "Userdaten Mobil:" + Environment.NewLine + txtEmail_M.Text + Environment.NewLine + txt_Username_M.Text)
            If String.IsNullOrEmpty(email) = False And String.IsNullOrEmpty(tokenname) = True And String.IsNullOrEmpty(password) = True And String.IsNullOrEmpty(username) = False And String.IsNullOrEmpty(customerID) = False Then
                If HttpContext.Current.Request.ServerVariables("SERVER_NAME") = "localhost" Then
                    VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = True
                    'ConnectionString = "Server=DEVELOPER\DEVSQL;Database=VERAG_HOMEPAGE;Uid=sa;Pwd=BmWr501956"
                    ConnectionString = "Server=DEVELOPER\DEVSQL;Database=VERAG_HOMEPAGE;Uid=AppUser;Pwd=yp/THDd?xM+pZ$;"
                Else
                    VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                    ConnectionString = "Server=DEVELOPER.verag.ost.dmn\DEVSQL;Database=VERAG_HOMEPAGE;Uid=AppUser;Pwd=yp/THDd?xM+pZ$;"
                    'ConnectionString = "Server=db593295684.db.1and1.com;Database=db593295684;Uid=dbo593295684;Pwd=atilla#2;"
                End If

                Using con As New SqlConnection(ConnectionString)
                    ' Using cmd As New SqlCommand("Validate_User")
                    Using cmd As New SqlCommand("SELECT UserId,Username,Password,Email,KundenNr FROM [VERAG_HOMEPAGE].[dbo].[Users] WHERE Username=@Username AND Email=@Email AND KundenNr=@CUSTOMERId")
                        ' cmd.CommandType = CommandType.StoredProcedure
                        cmd.Parameters.AddWithValue("@Username", username)
                        cmd.Parameters.AddWithValue("@Email", email)
                        cmd.Parameters.AddWithValue("@CUSTOMERId", customerID)
                        cmd.Connection = con
                        con.Open()
                        'userId = Convert.ToInt32(cmd.ExecuteScalar())
                        Dim dr As SqlDataReader = cmd.ExecuteReader()
                        If dr.Read() Then
                            username = dr("Username").ToString()
                            password = dr("Password").ToString()
                            email = dr("Email").ToString()
                            customerID = dr("KundenNr").ToString()
                            UserID = dr("UserId").ToString()

                            Try
                                If txt_Username.Text = dr("Username").ToString() AndAlso String.IsNullOrEmpty(txt_Username_M.Text) = True And String.IsNullOrEmpty(customerID) = False And String.IsNullOrEmpty(UserID) = False Then
                                    username = txt_Username.Text
                                    isusrnmright = True
                                ElseIf String.IsNullOrEmpty(txt_Username.Text) = True Then
                                    check_UserName_regex.MatchTimeout = 3000
                                    VERAG_VARIABLES.seterrorcount(5)
                                    check_UserName_regex.ErrorMessage = VERAG_VARIABLES.geterrornumb + "No Username was found!"
                                    isusrnmright = False
                                    Try
                                        check_UserName_regex.Validate()
                                    Catch
                                        isusrnmright = False
                                    End Try
                                End If
                                If (txtEmail.Text = dr("Email").ToString() AndAlso String.IsNullOrEmpty(txtEmail_M.Text) = True) And String.IsNullOrEmpty(UserID) = False Then
                                    email = txtEmail.Text
                                    lblMessage.ForeColor = Color.Green
                                    isemailright = True
                                    lblMessage.Text = "This email is from you!"
                                ElseIf String.IsNullOrEmpty(email) = True Then
                                    lblMessage.ForeColor = Color.Red
                                    isemailright = False
                                    VERAG_VARIABLES.seterrorcount(6)
                                    lblMessage.Text = VERAG_VARIABLES.geterrornumb + "The e-mail does not match with the given User."
                                Else
                                    lblMessage_M.ForeColor = Color.Red
                                    isemailright = False
                                    VERAG_VARIABLES.seterrorcount(7)
                                    lblMessage.Text = VERAG_VARIABLES.geterrornumb + "This e-mail address does not exist."
                                End If
                                If (txt_CustomerID.Text = dr("KundenNr").ToString() AndAlso String.IsNullOrEmpty(txt_CustomerID_M.Text) = True) And String.IsNullOrEmpty(UserID) = False Then
                                    customerID = txt_CustomerID.Text
                                    lblMessage.ForeColor = Color.Green
                                    isCustomeridright = True
                                ElseIf String.IsNullOrEmpty(customerID) = True Then
                                    lblMessage_M.ForeColor = Color.Red
                                    isCustomeridright = False
                                    VERAG_VARIABLES.seterrorcount(9)
                                    lblMessage.Text = VERAG_VARIABLES.geterrornumb + "The Customer-ID you entered is wrong."
                                Else
                                    lblMessage.ForeColor = Color.Red
                                    isCustomeridright = False
                                    VERAG_VARIABLES.seterrorcount(8)
                                    lblMessage.Text = VERAG_VARIABLES.geterrornumb + "Not such a Customer-ID is known."
                                End If
                            Catch ex As Exception
                                VERAG_VARIABLES.seterrorcount(408)
                                Title = VERAG_VARIABLES.geterrornumb() + "Authentification-Error!"
                                'MsgBox(Msg, Style, Title)
                                'If MsgBox(Msg, Style, Title).Yes Then
                                'txtEmail.Text = String.Empty
                                'txtEmail.Focus()
                                'ElseIf MsgBox(Msg, Style, Title).No Then
                                'End If
                            End Try
                        End If
                    End Using
                    con.Close()
                End Using

                If Session.Item("TokenforEmail") = Nothing Then
                    tokenname = genToken(username, password, email, customerID, isusrnmright, isCustomeridright, isemailright, Session.IsNewSession, UserID)
                    Session.Add("TokenforEmail", tokenname)
                    Session.Add("SessID", VERAG_PROG_ALLGEMEIN.cCryptography.Encrypt(Session.SessionID))
                Else
                    tokenname = Session.Item("TokenforEmail")
                End If
                Dim intzahl As Integer = VERAG_VARIABLES.RandomInteger(Math.Pow(2, 4), Math.Pow(2, 10))
                Dim hashdata As Byte() = Await VERAG_VARIABLES.HashPassword(tokenname, salt, VERAG_VARIABLES.getiterationnumber, intzahl)
                Session.Add("TokenHashtokenized", VERAG_PROG_ALLGEMEIN.cCryptography3.Encrypt(Convert.ToBase64String(hashdata)))
                If SendEmail(username, password, email, tokenname, customerID, isusrnmright, isCustomeridright, isemailright, Session.IsNewSession, UserID) = True Then
                    'password = RandomString(New Random, 10)
                    If (getDateoftoken(tokenname) = True) Then
                        'Dim msgboxstyle = vbDefaultButton1 + vbOK
                        'MsgBox(tokenname, msgboxstyle)
                        lblMessage.ForeColor = Color.Green
                        lblMessage.Text = "Token Generation successful."
                        'MsgBox("Token generated successfully.")
                    Else
                        lblMessage.ForeColor = Color.Red
                        VERAG_VARIABLES.seterrorcount(14)
                        lblMessage.Text = VERAG_VARIABLES.geterrornumb + "The Token is too old or not valid anymore. Please generate new Link by enter your data again!"
                        'btn hier einfügen
                        'MsgBox("Token is not valid anymore. Please generate a new one by sending a new e-mail!")

                        If Session.Item("TokenforEmail") = Nothing Then
                            tokenname = genToken(username, password, email, customerID, isusrnmright, isCustomeridright, isemailright, Session.IsNewSession, UserID)
                            Session.Add("TokenforEmail", tokenname)
                        Else
                            tokenname = Session.Item("TokenforEmail")
                        End If
                    End If
                    'SendEmail(username, password, email)
                    'MsgBox("Mail would be sent successfully!")
                    lblMessage.ForeColor = Color.Green
                    lblMessage.Text = "The Password-Reset-Link has been mailed to the valid Address given."
                ElseIf SendEmail(username, password, email, tokenname, customerID, isusrnmright, isCustomeridright, isemailright, Session.IsNewSession, UserID) = True Then
                    'MsgBox("Mail would not be sent successfully!")
                    lblMessage.ForeColor = Color.Red
                    If String.IsNullOrWhiteSpace(username) = True Then
                        VERAG_VARIABLES.seterrorcount(10)
                        lblMessage.Text = VERAG_VARIABLES.geterrornumb + "Username was not recognized!"
                    ElseIf String.IsNullOrWhiteSpace(email) = True Then
                        lblMessage.ForeColor = Drawing.Color.Red
                        VERAG_VARIABLES.seterrorcount(11)
                        lblMessage.Text = VERAG_VARIABLES.geterrornumb + "Email: Not recognized!"
                    ElseIf String.IsNullOrWhiteSpace(password) = True Then
                        lblMessage.ForeColor = Drawing.Color.Red
                        VERAG_VARIABLES.seterrorcount(12)
                        lblMessage.Text = VERAG_VARIABLES.geterrornumb + "An intern error has occured!" + Environment.NewLine + "Please contact an admin."
                        'Button
                    End If
                End If
            Else
                lblMessage.ForeColor = Drawing.Color.Red
                VERAG_VARIABLES.seterrorcount(13)
                lblMessage.Text = VERAG_VARIABLES.geterrornumb + "Database-Error."
                'Button
            End If
        Catch Exc As Exception
            lblMessage.ForeColor = Drawing.Color.Red
            VERAG_VARIABLES.seterrorcount(8)
            lblMessage.Text = VERAG_VARIABLES.geterrornumb + "No input found." + Environment.NewLine + Exc.Message
        End Try
    End Sub

    Protected Sub btn_Send_M_Click(sender As Object, e As EventArgs)

        Dim username As String = String.Empty
        Dim password As String = String.Empty
        Dim email As String = String.Empty
        Dim tokenname As String = String.Empty
        Dim customerID As String = String.Empty
        Dim UserID As String = String.Empty
        Dim isusernameright As Boolean = False
        Dim isuserIDright As Boolean = False
        Dim isuserEmailright As Boolean = False
        CustomerID_M_required.Validate()
        valreqtxtusername_M.Validate()
        valid_getNumber_M_Input.Validate()
        'Mobil
        If String.IsNullOrEmpty(txtEmail_M.Text) = False And String.IsNullOrEmpty(txt_Username_M.Text) = False And String.IsNullOrEmpty(txt_CustomerID_M.Text) = False And String.IsNullOrEmpty(txtEmail.Text) = True And String.IsNullOrEmpty(txt_Username.Text) = True And String.IsNullOrEmpty(txt_CustomerID.Text) = True Then
            valreqtxtusername.Enabled = False
            valreqtxtEmail.Enabled = False
            regexval_txt_Email_2.Enabled = False
            regexval_txt_Email.Enabled = False
            check_UserName_regex.Enabled = False
            CustomerIDrequired.Enabled = False
            valid_getNumberInput.Enabled = False

            regexval_2_txt_Email_M.Enabled = True
            regexval_txt_Email_M.Enabled = True
            valreqtxtEmail_M.Enabled = True
            valreqtxtusername_M.Enabled = True
            check_UserName_regex_M.Enabled = True
            CustomerID_M_required.Enabled = True
            valid_getNumber_M_Input.Enabled = True

            valreqtxtEmail_M.Validate()
            If valreqtxtEmail_M.IsValid = True Then
                regexval_txt_Email_M.Validate()
                If regexval_txt_Email_M.IsValid = True Then
                    regexval_txt_Email_M.ForeColor = Drawing.Color.OrangeRed
                    VERAG_VARIABLES.seterrorcount(15)
                    regexval_txt_Email_M.ErrorMessage = VERAG_VARIABLES.geterrornumb + "Die Kundennummer ist nicht numerisch oder zu lang."
                    regexval_2_txt_Email_M.Validate()
                    If regexval_2_txt_Email_M.IsValid = True Then
                        email = txtEmail_M.Text
                        lblMessage_M.ForeColor = Drawing.Color.Green
                        lblMessage_M.Text = "E-Mail Adresse ist validiert.."
                    End If
                Else
                    regexval_txt_Email.Validate()
                    If regexval_2_txt_Email_M.IsValid = True Then
                        lblMessage_M.ForeColor = Drawing.Color.Green
                        lblMessage_M.Text = "E-Mail Adresse ist korrekt."
                        email = txtEmail_M.Text
                    End If
                End If
            End If

            CustomerID_M_required.Validate()
            If CustomerID_M_required.IsValid = True Then
                valid_getNumber_M_Input.Validate()
                If valid_getNumber_M_Input.IsValid = True Then
                    customerID = txt_CustomerID_M.Text
                Else
                    lblMessage_M.ForeColor = Drawing.Color.Red
                    VERAG_VARIABLES.seterrorcount(16)
                    lblMessage_M.Text = VERAG_VARIABLES.geterrornumb + "Die Benutzerkennung ist zu lange oder ungültig."
                End If
            End If

            valreqtxtusername_M.Validate()
            If valreqtxtusername_M.IsValid = True Then
                check_UserName_regex_M.Validate()
                If check_UserName_regex_M.IsValid = False Then
                    check_UserName_regex_M.ForeColor = Drawing.Color.Red
                    VERAG_VARIABLES.seterrorcount(17)
                    check_UserName_regex_M.ErrorMessage = VERAG_VARIABLES.geterrornumb + "Der Benutzername ist zu lang."
                Else
                    username = txt_Username_M.Text
                    lblMessage_M.ForeColor = Drawing.Color.Green
                    lblMessage_M.Text = "Ein korrekter Benutzername ist eingegeben worden."
                End If
            End If
        Else
            'MsgBox("The form has not been filled completeley.", MsgBoxStyle.Critical, "Error08")
            lblMessage_M.ForeColor = Color.Red
            VERAG_VARIABLES.seterrorcount(8)
            lblMessage_M.Text = "Error 08. The form has not been filled completeley."
        End If

        'Erweiterte Debug Msg-Box
        'MsgBox("Userdaten in App" + Environment.NewLine + email + Environment.NewLine + username + Environment.NewLine + "Userdaten desktop" + txt_Username.Text + Environment.NewLine + txtEmail.Text + Environment.NewLine + "Userdaten Mobil:" + Environment.NewLine + txtEmail_M.Text + Environment.NewLine + txt_Username_M.Text)
        If String.IsNullOrEmpty(tokenname) = True And String.IsNullOrEmpty(password) = True Then
            If HttpContext.Current.Request.ServerVariables("SERVER_NAME") = "localhost" Then
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = True
                'ConnectionString = "Server=DEVELOPER\DEVSQL;Database=VERAG_HOMEPAGE;Uid=sa;Pwd=BmWr501956"
                ConnectionString = "Server=DEVELOPER\DEVSQL;Database=VERAG_HOMEPAGE;Uid=AppUser;Pwd=yp/THDd?xM+pZ$;"
            Else
                VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM = False
                ConnectionString = "Server=DEVELOPER.verag.ost.dmn\DEVSQL;Database=VERAG_HOMEPAGE;Uid=AppUser;Pwd=yp/THDd?xM+pZ$;"
                'ConnectionString = "Server=db593295684.db.1and1.com;Database=db593295684;Uid=dbo593295684;Pwd=atilla#2;"
            End If

            Using con As New SqlConnection(ConnectionString)
                ' Using cmd As New SqlCommand("Validate_User")
                Using cmd As New SqlCommand("SELECT Username,Password,Email,KundenNr,UserId FROM [VERAG_HOMEPAGE].[dbo].[Users] WHERE Username=@Username AND Email=@Email AND KundenNr=@CUSTOMERId")
                    ' cmd.CommandType = CommandType.StoredProcedure
                    cmd.Parameters.AddWithValue("@Username", username)
                    cmd.Parameters.AddWithValue("@Email", email)
                    cmd.Parameters.AddWithValue("@CUSTOMERId", customerID)
                    cmd.Connection = con
                    con.Open()
                    'userId = Convert.ToInt32(cmd.ExecuteScalar())
                    Dim dr As SqlDataReader = cmd.ExecuteReader()
                    If dr.Read() Then
                        username = dr("Username").ToString()
                        password = dr("Password").ToString()
                        email = dr("Email").ToString()
                        customerID = dr("KundenNr").ToString()
                        UserID = dr("UserId").ToString()
                        Try
                            If (txt_CustomerID_M.Text = dr("KundenNr").ToString() AndAlso String.IsNullOrEmpty(txt_CustomerID.Text) = True) And String.IsNullOrEmpty(customerID) = False And String.IsNullOrEmpty(UserID) = False Then
                                customerID = txt_CustomerID_M.Text
                                lblMessage_M.ForeColor = Color.Green
                                isuserIDright = True
                                lblMessage_M.Text = "The given Customer-ID exists in our database."
                            Else
                                lblMessage_M.ForeColor = Color.Red
                                isuserIDright = False
                                VERAG_VARIABLES.seterrorcount(18)
                                lblMessage_M.Text = VERAG_VARIABLES.geterrornumb + "The given Customer-ID does not exist in our database."
                                Return
                            End If
                        Catch ex As Exception
                            Dim Msg, Style, Title As String
                            Msg = "Customer-ID validation failed!" & vbCrLf + "Please try again!"
                            Style = vbRetry + vbExclamation + vbDefaultButton1
                            Title = "Authentication error!"
                        End Try
                        Try
                            If (txtEmail_M.Text = dr("Email").ToString() AndAlso String.IsNullOrEmpty(txtEmail.Text) = True) And String.IsNullOrEmpty(customerID) = False Then
                                email = txtEmail_M.Text
                                isuserEmailright = True
                                lblMessage_M.ForeColor = Color.Green
                                lblMessage_M.Text = "The given e-mail exists in our database."
                            Else
                                lblMessage_M.ForeColor = Color.Red
                                isuserEmailright = False
                                VERAG_VARIABLES.seterrorcount(19)
                                lblMessage_M.Text = VERAG_VARIABLES.geterrornumb + "The given E-Mail does not exist in our database."
                                Return
                            End If
                        Catch ex As Exception
                            Dim Msg, Style, Title As String
                            Msg = "E-Mail validation failed!" & vbCrLf + "Please try again!"
                            Style = vbRetry + vbExclamation + vbDefaultButton1
                            Title = "Authentication error!"
                        End Try
                        Try
                            If (txt_Username_M.Text = dr("Username").ToString() AndAlso String.IsNullOrEmpty(txt_Username.Text) = True) And String.IsNullOrEmpty(customerID) = False Then
                                username = txt_Username_M.Text
                                lblMessage_M.ForeColor = Color.Green
                                isusernameright = True
                                lblMessage_M.Text = "The given Username exists in our database."
                            Else
                                lblMessage_M.ForeColor = Color.Red
                                isusernameright = False
                                VERAG_VARIABLES.seterrorcount(20)
                                lblMessage_M.Text = VERAG_VARIABLES.geterrornumb + "The given Username does not exist in our database."
                            End If
                        Catch ex As Exception
                            Dim Msg, Style, Title As String
                            Msg = "Username validation failed!" & vbCrLf + "Please try again!"
                            Style = vbRetry + vbExclamation + vbDefaultButton1
                            Title = "Authentication error!"
                        End Try
                    End If
                End Using
                con.Close()
            End Using

            If Session.Item("TokenforEmail") = Nothing Then
                tokenname = genToken(username, password, email, customerID, isusernameright, isuserIDright, isuserEmailright, Session.IsNewSession, UserID)
                Session.Add("TokenforEmail", tokenname)
                Session.Add("SessID", VERAG_PROG_ALLGEMEIN.cCryptography.Encrypt(Session.SessionID))
            Else
                tokenname = Session.Item("TokenforEmail")
            End If
            'Dim md5temptoken As String

            'md5temptoken = Await Findtokenhashsalt(username, password, email, customerID, isusernameright, isuserIDright, isuserEmailright, Session.IsNewSession, UserID)

            'md5temptoken = gensaltToken(username, password, email, customerID, isusernameright, isuserIDright, isuserEmailright, Session.IsNewSession, UserID)
            'MsgBox("Token:" + tokenname + Environment.NewLine + "md5" + md5temptoken)

            If SendEmail_M(username, password, email, tokenname, customerID, isusernameright, isuserIDright, isuserEmailright, Session.IsNewSession, UserID) = True Then
                'password = RandomString(New Random, 10)
                If (getDateoftoken(tokenname) = True) Then
                    'Dim msgboxstyle = vbDefaultButton1 + vbOK
                    'MsgBox(tokenname, msgboxstyle)
                    lblMessage_M.ForeColor = Color.Green
                    lblMessage_M.Text = "Token generated successfully."
                    'MsgBox("Token generated successfully.")
                Else
                    lblMessage_M.ForeColor = Color.Red
                    VERAG_VARIABLES.seterrorcount(100)
                    lblMessage_M.Text = VERAG_VARIABLES.geterrornumb + "Token is not valid anymore. Please generate a new one by sending a new e-mail!"
                    'MsgBox("Token is not valid anymore. Please generate a new one by sending a new e-mail!")

                    If Session.Item("TokenforEmail") = Nothing Then
                        tokenname = genToken(username, password, email, customerID, isusernameright, isuserIDright, isuserEmailright, Session.IsNewSession, UserID)
                        Session.Add("TokenforEmail", tokenname)
                    Else
                        tokenname = Session.Item("TokenforEmail")
                    End If
                End If
                'SendEmail(username, password, email)
                'MsgBox("Mail would be sent successfully!")
                lblMessage_M.ForeColor = Color.Green
                lblMessage_M.Text = "The Password-Reset-Link has been mailed to the valid E-Mail Address given."
            ElseIf SendEmail_M(username, password, email, tokenname, customerID, isusernameright, isuserIDright, isuserEmailright, Session.IsNewSession, UserID) = True Then
                'MsgBox("Mail would not be sent successfully!")
                lblMessage_M.ForeColor = Color.Red
                If String.IsNullOrWhiteSpace(username) = True Then
                    lblMessage_M.ForeColor = Drawing.Color.Red
                    VERAG_VARIABLES.seterrorcount(10)
                    lblMessage_M.Text = VERAG_VARIABLES.geterrornumb + "Username not recognized Error!"
                ElseIf String.IsNullOrWhiteSpace(email) = True Then
                    lblMessage_M.ForeColor = Drawing.Color.Red
                    VERAG_VARIABLES.seterrorcount(11)
                    lblMessage_M.Text = VERAG_VARIABLES.geterrornumb + "Email not recognized Error!"
                ElseIf String.IsNullOrWhiteSpace(password) = True Then
                    lblMessage_M.ForeColor = Drawing.Color.Red
                    VERAG_VARIABLES.seterrorcount(12)
                    lblMessage_M.Text = VERAG_VARIABLES.geterrornumb + "An internal password searching error occured in our systems ."
                End If
            End If
        Else
            lblMessage_M.ForeColor = Drawing.Color.Red
            VERAG_VARIABLES.seterrorcount(15)
            lblMessage_M.Text = VERAG_VARIABLES.geterrornumb + "Error with Database or the connection." + Environment.NewLine + "Please contact the admin."
        End If
    End Sub

    Function SendEmail_M(username As String, password As String, email As String, tokenname As String, customerID As String, isusrnmright As Boolean, iscstmIDright As Boolean, isemailright As Boolean, sessionisnew As Boolean, theUserID As String) As Boolean
        Dim getdomianenvironment As String = String.Empty
        Dim pagename As String = String.Empty
        Dim ServPort As String = String.Empty
        Dim mailto As String = String.Empty
        Dim Betreff As String = String.Empty
        Dim htmlbody As String = String.Empty
        Dim emailnr = VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA_ID.ToString
        If isusrnmright = True And iscstmIDright = True AndAlso isemailright = True And sessionisnew = False AndAlso String.IsNullOrEmpty(theUserID) = False And String.IsNullOrEmpty(customerID) = False Then
            If HttpContext.Current.Request.ServerVariables("SERVER_NAME") = "localhost" Then
                'MsgBox(getdomianenvironment)
                getdomianenvironment = HttpContext.Current.Request.ServerVariables("SERVER_NAME")
                ServPort = ":" + Request.ServerVariables("SERVER_PORT")
                'pagename = Request.ServerVariables("SCRIPT_NAME")
                mailto = email
                Betreff = "Passwort reset"
                Dim mailpic As String = "<image src=" + "../images/VERAG_AEO_MailSig.jpg" + ">"
                Dim Ausschusstext As String = "Wir arbeiten ausschließlich auf Grund der Allgemeinen Spediteurbedingungen in der jeweils geltenden Fassung. Zahlungen werden zunächst auf Frachten, Spesen"
                Dim Ausschusstext2 As String = "und Zinsen zuletzt auf Zölle angerechnet. Zahlbar und klagbar in Schärding oder Ried. Steuer-Zoll-und Tarifauskünfte sind unverbindlich."
                Dim Ausschusstext3 As String = "We operate exclusively on the basis of the General Freight Forwarding Terms and Conditions in the respectively applicable version. Payments are initially"
                Dim Ausschusstext4 As String = "charged on freight, fees and interests and at last on customs duties. The place of jurisdiction: Schärding / Ried. Tax, customs and tariff information are not binding."
                htmlbody = String.Format("Dear {0}," + Environment.NewLine + Environment.NewLine + " Please follow the Link to reset your password:<br />" + Environment.NewLine + "<a runat=" + "server" + " href=http://" + getdomianenvironment + ServPort + "/login/Change_PW.aspx?Par1=" + tokenname + "&Par2=" + VERAG_PROG_ALLGEMEIN.cCryptography.Encrypt(username) + "&Par3=" + VERAG_PROG_ALLGEMEIN.cCryptography2.Encrypt(customerID) + "&Mob=" + VERAG_PROG_ALLGEMEIN.cCryptography2.Encrypt("False") + "&Par4=" + VERAG_PROG_ALLGEMEIN.cCryptography3.Encrypt(theUserID) + "&Par5=" + VERAG_PROG_ALLGEMEIN.cCryptography2.Encrypt(email) + ">http://" + getdomianenvironment + ServPort + "/login/ChangePW.aspx?Par1=" + VERAG_PROG_ALLGEMEIN.cCryptography.Encrypt(tokenname) + "&Par2=" + VERAG_PROG_ALLGEMEIN.cCryptography.Encrypt(username) + "&Par3=" + VERAG_PROG_ALLGEMEIN.cCryptography2.Encrypt(customerID) + "&Mob=" + VERAG_PROG_ALLGEMEIN.cCryptography2.Encrypt("False") + "&Par4=" + VERAG_PROG_ALLGEMEIN.cCryptography3.Encrypt(theUserID) + "&Par5=" + VERAG_PROG_ALLGEMEIN.cCryptography2.Encrypt(email) + "</a>" + Environment.NewLine + "<br /><br />Notice:<br /><span style='color: #043381;font-size:14px'><i>The Link is valid for 30 minutes until" + Space(1) + Date.Now.AddMinutes(30).ToString() + Space(1) + "only!</i></span><br / >To resend the E-Mail: <a runat=" + "server" + " href=http://" + getdomianenvironment + ServPort + "/login/ForgotPW.aspx>Follow this Link</a><br /><br />Kind regards, <br /><span style='color: #043381'><b>VERAG | EDV Support</b></span><br /><span>" + mailpic + "</span><br /><span style='color: #043381'>VERAG Spedition AG | A 4975 Suben, Nr. 100</span><br /><span style='color: #043381'>T.<a href='tel:+43 7711 2777-xx'>+43 7711 2777-xx</a> |<a href='mailto:@support@verag.ag'>support@verag.ag</a> |" + emailnr + "FN xxxxxxx</span><br /><span style='color: #043381;font-size:12px'><i>" + Ausschusstext + "</i></span><br /><span style='color: #043381;font-size:12px'><i>" + Ausschusstext2 + "</i></span><br /><span style='color: #043381;font-size:12px'><i>" + Ausschusstext3 + "</i></span><br /><span style='color: #043381;font-size:12px'><i>" + Ausschusstext4 + "</i></span><br />", username, password)
            ElseIf String.IsNullOrEmpty(HttpContext.Current.Request.ServerVariables("SERVER_NAME")) = False Then
                getdomianenvironment = HttpContext.Current.Request.ServerVariables("SERVER_NAME")
                'MsgBox(getdomianenvironment)
                ServPort = ":" + Request.ServerVariables("SERVER_PORT")
                'pagename = Request.ServerVariables("SCRIPT_NAME")
                mailto = email
                Betreff = "Passwort reset"
                Dim mailpic As String = "<image src=" + "../images/VERAG_AEO_MailSig.jpg" + ">"
                Dim Ausschusstext As String = "Wir arbeiten ausschließlich auf Grund der Allgemeinen Spediteurbedingungen in der jeweils geltenden Fassung. Zahlungen werden zunächst auf Frachten, Spesen"
                Dim Ausschusstext2 As String = "und Zinsen zuletzt auf Zölle angerechnet. Zahlbar und klagbar in Schärding oder Ried. Steuer-Zoll-und Tarifauskünfte sind unverbindlich."
                Dim Ausschusstext3 As String = "We operate exclusively on the basis of the General Freight Forwarding Terms and Conditions in the respectively applicable version. Payments are initially"
                Dim Ausschusstext4 As String = "charged on freight, fees and interests and at last on customs duties. The place of jurisdiction: Schärding / Ried. Tax, customs and tariff information are not binding."
                htmlbody = String.Format("Dear {0}," + Environment.NewLine + Environment.NewLine + " Please follow the Link to reset your password:<br />" + Environment.NewLine + "<a runat=" + "server" + " href=http://" + getdomianenvironment + "/login/Change_PW.aspx?Par1=" + tokenname + "&Par2=" + VERAG_PROG_ALLGEMEIN.cCryptography.Encrypt(username) + "&Par3=" + VERAG_PROG_ALLGEMEIN.cCryptography2.Encrypt(customerID) + "&Mob=" + VERAG_PROG_ALLGEMEIN.cCryptography2.Encrypt("False") + "&Par4=" + VERAG_PROG_ALLGEMEIN.cCryptography3.Encrypt(theUserID) + "&Par5=" + VERAG_PROG_ALLGEMEIN.cCryptography2.Encrypt(email) + ">http://" + getdomianenvironment + ServPort + "/login/ChangePW.aspx?Par1=" + tokenname + "&Par2=" + VERAG_PROG_ALLGEMEIN.cCryptography.Encrypt(username) + "&Par3=" + VERAG_PROG_ALLGEMEIN.cCryptography2.Encrypt(customerID) + "&Mob=" + VERAG_PROG_ALLGEMEIN.cCryptography2.Encrypt("False") + "&Par4=" + VERAG_PROG_ALLGEMEIN.cCryptography3.Encrypt(theUserID) + "&Par5=" + VERAG_PROG_ALLGEMEIN.cCryptography2.Encrypt(email) + "</a>" + Environment.NewLine + "<br /><br />Notice:<br /><span style='color: #043381;font-size:14px'><i>The Link is valid for 30 minutes until" + Space(1) + Date.Now.AddMinutes(30).ToString() + Space(1) + "only!</i></span><br / >To resend the E-Mail: <a runat=" + "server" + " href=http://" + getdomianenvironment + "/login/ForgotPW.aspx>Follow this Link</a><br />Kind regards, <br /><span style='color: #043381'><b>VERAG | EDV Support</b></span><br /><span>" + mailpic + "</span><br /><span style='color: #043381'>VERAG Spedition AG | A 4975 Suben, Nr. 100</span><br /><span style='color: #043381'>T.<a href='tel:+43 7711 2777-xx'>+43 7711 2777-xx</a> |<a href='mailto:@support@verag.ag'>support@verag.ag</a> | " + emailnr + "FN xxxxxxx</span><br /><span style='color: #043381;font-size:12px'><i>" + Ausschusstext + "</i></span><br /><span style='color: #043381;font-size:12px'><i>" + Ausschusstext2 + "</i></span><br /><span style='color: #043381;font-size:12px'><i>" + Ausschusstext3 + "</i></span><br /><span style='color: #043381;font-size:12px'><i>" + Ausschusstext4 + "</i></span><br />", username, password)
            ElseIf String.IsNullOrWhiteSpace(HttpContext.Current.Request.ServerVariables("SERVER_NAME")) = True Then
                'MsgBox("Error09:" + Environment.NewLine + "The Domain could not be vaildated. Check Link please or contact the Administrator of the program.")
                lblMessage_M.ForeColor = Color.OrangeRed
                VERAG_VARIABLES.seterrorcount(9)
                lblMessage_M.Text = VERAG_VARIABLES.geterrornumb() + Environment.NewLine + "The Domain could not be vaildated. Check the Link please or contact the Administrator of the program."
            End If
            'Dim pg As String = Request.ServerVariables("URL")
            'MsgBox("/" + ServPort + Request.ServerVariables("URL"))

            Try
                If Session.Item("TokenforEmail") = Nothing Then
                    tokenname = genToken(username, password, email, customerID, isusrnmright, iscstmIDright, isemailright, Session.IsNewSession, theUserID)
                    Session.Add("TokenforEmail", tokenname)
                Else
                    tokenname = Session.Item("TokenforEmail").ToString()
                End If
                'Dim Strtemp = Session.Keys.Item("urltochangepw")
                If getDateoftoken(tokenname) = True Then
                    '  Dim attachment As Attachment = New Attachment(File.OpenRead(excel), "Kundenliste.xlsx")
                    '  Msg.Attachments.Add(attachment)
                    If String.IsNullOrEmpty(mailto) = False AndAlso String.IsNullOrEmpty(Betreff) = False AndAlso String.IsNullOrEmpty(htmlbody) = False Then
                        VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(mailto, Betreff, htmlbody)
                    Else
                        'MsgBox("Error07: Die Paramter wurden nicht alle gesetzt. Bitte Felder überprüfen.", vbAbort, "Error07")
                        lblMessage_M.ForeColor = Color.OrangeRed
                        VERAG_VARIABLES.seterrorcount(7)
                        lblMessage_M.Text = VERAG_VARIABLES.geterrornumb + "The form has not been filled out completely."
                    End If
                    lblMessage_M.ForeColor = Color.Green
                    lblMessage_M.Text = "Success" + Environment.NewLine + "The Password-Reset-Link has been mailed to the valid Address given."
                    'MsgBox("SENT")
                    Return True
                Else
                    lblMessage_M.ForeColor = Color.Red
                    VERAG_VARIABLES.seterrorcount(2)
                    lblMessage_M.Text = VERAG_VARIABLES.geterrornumb + "Mail not delivered!"
                    'MsgBox("Error02: Mail not delivered!" & vbCrLf & "New Token has been generated.")
                    If Session.Item("TokenforEmail") = Nothing Then
                        tokenname = genToken(username, password, email, customerID, isusrnmright, iscstmIDright, isemailright, Session.IsNewSession, theUserID)
                        Session.Add("TokenforEmail", tokenname)
                        Session.Add("USerID", customerID)
                    Else
                        tokenname = Session.Item("TokenforEmail").ToString()
                    End If
                    VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(mailto, Betreff, htmlbody)
                    Return True
                End If
            Catch ex As Exception

                'MsgBox(Err.Number & ex.Message & ex.StackTrace.ToString) 'Falls ein Fehler auftritt wird eine MsgBox angezeigt
            End Try
            Return True
        Else
            Return False
        End If
    End Function

    Async Function Findtokenhashsalt(username As String, password As String, email As String, customerID As String, isusernameright As Boolean, isuserIDright As Boolean, isuserEmailright As Boolean, isnewsess As Boolean, UserID As String) As Task(Of String)
        Dim t As Task(Of String)
        t = Task.Run(Async Function() As Task(Of String)
                         Return Await gensaltToken(username, password, email, customerID, isusernameright, isuserIDright, isuserEmailright, isnewsess, UserID)
                     End Function)
        Return Await t
    End Function
    Function SendEmail(username As String, password As String, email As String, tokenname As String, customerID As String, isusrnmright As Boolean, iscstmIDright As Boolean, isemailright As Boolean, sessionisnew As Boolean, theUserID As String) As Boolean
        Dim getdomianenvironment As String = String.Empty
        Dim pagename As String = String.Empty
        Dim ServPort As String = String.Empty
        Dim mailto As String = String.Empty
        Dim Betreff As String = String.Empty
        Dim htmlbody As String = String.Empty
        Dim emailnr = VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA_ID.ToString
        If isusrnmright = True And iscstmIDright = True AndAlso isemailright = True And sessionisnew = False AndAlso String.IsNullOrEmpty(theUserID) = False And String.IsNullOrEmpty(customerID) = False Then
            If HttpContext.Current.Request.ServerVariables("SERVER_NAME") = "localhost" Then
                'MsgBox(getdomianenvironment)
                getdomianenvironment = HttpContext.Current.Request.ServerVariables("SERVER_NAME")
                ServPort = ":" + Request.ServerVariables("SERVER_PORT")
                'pagename = Request.ServerVariables("SCRIPT_NAME")
                mailto = email
                Betreff = "VERAG Spedition Password reset"
                Dim mailpic As String = "<image src=" + "../images/VERAG_AEO_MailSig.jpg" + ">"
                Dim Ausschusstext As String = "Wir arbeiten ausschließlich auf Grund der Allgemeinen Spediteurbedingungen in der jeweils geltenden Fassung. Zahlungen werden zunächst auf Frachten, Spesen"
                Dim Ausschusstext2 As String = "und Zinsen zuletzt auf Zölle angerechnet. Zahlbar und klagbar in Schärding oder Ried. Steuer-Zoll-und Tarifauskünfte sind unverbindlich."
                Dim Ausschusstext3 As String = "We operate exclusively on the basis of the General Freight Forwarding Terms and Conditions in the respectively applicable version. Payments are initially"
                Dim Ausschusstext4 As String = "charged on freight, fees and interests and at last on customs duties. The place of jurisdiction: Schärding / Ried. Tax, customs and tariff information are not binding."
                htmlbody = String.Format("Dear {0},<br /><br /> Please follow the Link to reset your password:<br /><br />" + Environment.NewLine + "<a runat=" + "server" + " href=http://" + getdomianenvironment + ServPort + "/login/Change_PW.aspx?Par1=" + tokenname + "&Par2=" + VERAG_PROG_ALLGEMEIN.cCryptography.Encrypt(username) + "&Par3=" + VERAG_PROG_ALLGEMEIN.cCryptography2.Encrypt(customerID) + "&Mob=" + VERAG_PROG_ALLGEMEIN.cCryptography2.Encrypt("False") + "&Par4=" + VERAG_PROG_ALLGEMEIN.cCryptography3.Encrypt(theUserID) + "&Par5=" + VERAG_PROG_ALLGEMEIN.cCryptography2.Encrypt(email) + ">http://" + getdomianenvironment + ServPort + "/login/ChangePW.aspx?Par1=" + tokenname + "&Par2=" + VERAG_PROG_ALLGEMEIN.cCryptography.Encrypt(username) + "&Par3=" + VERAG_PROG_ALLGEMEIN.cCryptography2.Encrypt(customerID) + "&Mob=" + VERAG_PROG_ALLGEMEIN.cCryptography2.Encrypt("False") + "&Par4=" + VERAG_PROG_ALLGEMEIN.cCryptography3.Encrypt(theUserID) + "&Par5=" + VERAG_PROG_ALLGEMEIN.cCryptography2.Encrypt(email) + "</a>" + Environment.NewLine + "<br /><br />Notice:<br /><span style='color: #043381;font-size:14px'><i>The Link is valid for 30 minutes until" + Space(1) + Date.Now.AddMinutes(30).ToString() + Space(1) + "only!</i></span><br / >To resend the E-Mail: <a runat=" + "server" + " href=http://" + getdomianenvironment + ServPort + "/login/ForgotPW.aspx>http://" + getdomianenvironment + ServPort + "/login/ForgotPW.aspx</a><br /><br />Kind regards, <br /><span style='color: #043381'><b>VERAG | EDV Support</b></span><br /><span>" + mailpic + "</span><br /><span style='color: #043381'>VERAG Spedition AG | A 4975 Suben, Nr. 100</span><br /><span style='color: #043381'>T.<a href='tel:+43 7711 2777-xx'>+43 7711 2777-xx</a> |<a href='mailto:@support@verag.ag'>support@verag.ag</a> |" + emailnr + "FN xxxxxxx</span><br /><span style='color: #043381;font-size:12px'><i>" + Ausschusstext + "</i></span><br /><span style='color: #043381;font-size:12px'><i>" + Ausschusstext2 + "</i></span><br /><span style='color: #043381;font-size:12px'><i>" + Ausschusstext3 + "</i></span><br /><span style='color: #043381;font-size:12px'><i>" + Ausschusstext4 + "</i></span><br />", username, password)
            ElseIf String.IsNullOrEmpty(HttpContext.Current.Request.ServerVariables("SERVER_NAME")) = False Then
                getdomianenvironment = HttpContext.Current.Request.ServerVariables("SERVER_NAME")
                'MsgBox(getdomianenvironment)
                ServPort = ":" + Request.ServerVariables("SERVER_PORT")
                'pagename = Request.ServerVariables("SCRIPT_NAME")
                mailto = email
                Betreff = "VERAG Spedition Password reset"
                Dim mailpic As String = "<image src=" + "../images/VERAG_AEO_MailSig.jpg" + ">"
                Dim Ausschusstext As String = "Wir arbeiten ausschließlich auf Grund der Allgemeinen Spediteurbedingungen in der jeweils geltenden Fassung. Zahlungen werden zunächst auf Frachten, Spesen"
                Dim Ausschusstext2 As String = "und Zinsen zuletzt auf Zölle angerechnet. Zahlbar und klagbar in Schärding oder Ried. Steuer-Zoll-und Tarifauskünfte sind unverbindlich."
                Dim Ausschusstext3 As String = "We operate exclusively on the basis of the General Freight Forwarding Terms and Conditions in the respectively applicable version. Payments are initially"
                Dim Ausschusstext4 As String = "charged on freight, fees and interests and at last on customs duties. The place of jurisdiction: Schärding / Ried. Tax, customs and tariff information are not binding."
                htmlbody = String.Format("Dear {0},<br /><br /> Please follow the Link to reset your password:<br /><br />" + Environment.NewLine + "<a runat=" + "server" + " href=http://" + getdomianenvironment + "/login/Change_PW.aspx?Par1=" + tokenname + "&Par2=" + VERAG_PROG_ALLGEMEIN.cCryptography.Encrypt(username) + "&Par3=" + VERAG_PROG_ALLGEMEIN.cCryptography2.Encrypt(customerID) + "&Mob=" + VERAG_PROG_ALLGEMEIN.cCryptography2.Encrypt("False") + "&Par4=" + VERAG_PROG_ALLGEMEIN.cCryptography3.Encrypt(theUserID) + "&Par5=" + VERAG_PROG_ALLGEMEIN.cCryptography2.Encrypt(email) + ">http://" + getdomianenvironment + ServPort + "/login/ChangePW.aspx?Par1=" + tokenname + "&Par2=" + VERAG_PROG_ALLGEMEIN.cCryptography.Encrypt(username) + "&Par3=" + VERAG_PROG_ALLGEMEIN.cCryptography2.Encrypt(customerID) + "&Mob=" + VERAG_PROG_ALLGEMEIN.cCryptography2.Encrypt("False") + "&Par4=" + VERAG_PROG_ALLGEMEIN.cCryptography3.Encrypt(theUserID) + "&Par5=" + VERAG_PROG_ALLGEMEIN.cCryptography2.Encrypt(email) + "</a>" + Environment.NewLine + "<br /><br />Notice:<br /><span style='color: #043381;font-size:14px'><i>The Link is valid for 30 minutes until" + Space(1) + Date.Now.AddMinutes(30).ToString() + Space(1) + "only!</i></span><br / >To resend the E-Mail: <a runat=" + "server" + " href=http://" + getdomianenvironment + "/login/ForgotPW.aspx>http://" + getdomianenvironment + "/login/ForgotPW.aspx</a><br /><br />Kind regards, <br /><span style='color: #043381'><b>VERAG | EDV Support</b></span><br /><span>" + mailpic + "</span><br /><span style='color: #043381'>VERAG Spedition AG | A 4975 Suben, Nr. 100</span><br /><span style='color: #043381'>T.<a href='tel:+43 7711 2777-xx'>+43 7711 2777-xx</a> |<a href='mailto:@support@verag.ag'>support@verag.ag</a> | " + emailnr + "FN xxxxxxx</span><br /><span style='color: #043381;font-size:12px'><i>" + Ausschusstext + "</i></span><br /><span style='color: #043381;font-size:12px'><i>" + Ausschusstext2 + "</i></span><br /><span style='color: #043381;font-size:12px'><i>" + Ausschusstext3 + "</i></span><br /><span style='color: #043381;font-size:12px'><i>" + Ausschusstext4 + "</i></span><br />", username, password)
            ElseIf String.IsNullOrWhiteSpace(HttpContext.Current.Request.ServerVariables("SERVER_NAME")) = True Then
                'MsgBox("Error09:" + Environment.NewLine + "The Domain could not be vaildated. Check Link please or contact the Administrator of the program.")
                lblMessage.ForeColor = Color.OrangeRed
                VERAG_VARIABLES.seterrorcount(9)
                lblMessage.Text = VERAG_VARIABLES.geterrornumb + Environment.NewLine + "The Domain could not be vaildated. Check the Link please or contact the Administrator of the program."
            End If
            'Dim pg As String = Request.ServerVariables("URL")
            'MsgBox("/" + ServPort + Request.ServerVariables("URL"))

            Try
                If Session.Item("TokenforEmail") = Nothing Then
                    tokenname = genToken(username, password, email, customerID, isusrnmright, iscstmIDright, isemailright, Session.IsNewSession, theUserID)
                    Session.Add("TokenforEmail", tokenname)
                Else
                    tokenname = Session.Item("TokenforEmail").ToString()
                End If

                'Dim Strtemp = Session.Keys.Item("urltochangepw")
                If getDateoftoken(tokenname) = True Then
                    '  Dim attachment As Attachment = New Attachment(File.OpenRead(excel), "Kundenliste.xlsx")
                    '  Msg.Attachments.Add(attachment)
                    If String.IsNullOrEmpty(mailto) = False AndAlso String.IsNullOrEmpty(Betreff) = False AndAlso String.IsNullOrEmpty(htmlbody) = False Then
                        VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(mailto, Betreff, htmlbody)
                    Else
                        'MsgBox("Error07: Die Paramter wurden nicht alle gesetzt. Bitte Felder überprüfen.", vbAbort, "Error07")
                        lblMessage.ForeColor = Color.OrangeRed
                        VERAG_VARIABLES.seterrorcount(7)
                        lblMessage.Text = VERAG_VARIABLES.geterrornumb + "Plaese check all fields."
                    End If
                    lblMessage.ForeColor = Color.Green
                    lblMessage.Text = "The Password-Reset-Link has been mailed to the valid Address given."
                    'MsgBox("SENT")
                    Return True
                Else
                    lblMessage.ForeColor = Color.Red
                    lblMessage.Text = "Error02: Mail not delivered!"
                    'MsgBox("Error02: Mail not delivered!" & vbCrLf & "New Token has been generated.")
                    If Session.Item("TokenforEmail") = Nothing Then
                        tokenname = genToken(username, password, email, customerID, isusrnmright, iscstmIDright, isemailright, Session.IsNewSession, theUserID)
                        Session.Add("TokenforEmail", tokenname)
                        Session.Add("USerID", customerID)
                    Else
                        tokenname = Session.Item("TokenforEmail").ToString()
                    End If
                    VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(mailto, Betreff, htmlbody)
                    Return True
                End If
            Catch ex As Exception
                'MsgBox(Err.Number & ex.Message & ex.StackTrace.ToString) 'Falls ein Fehler auftritt wird eine MsgBox angezeigt
                VERAG_VARIABLES.seterrorcount(12)
                lblMessage.Text = VERAG_VARIABLES.geterrornumb + "No Token could be generated! Try to contact the admin."
            End Try
            Return True
        Else
            Return False
        End If
    End Function

    Function genToken(username As String, password As String, email As String, CustomerID As String, isusrnmright As Boolean, iscstmIDright As Boolean, isemailright As Boolean, isnewSession As Boolean, theUserID As String) As String
        If isnewSession = False Then
            Dim time() As Byte = BitConverter.GetBytes(DateTime.UtcNow.ToBinary())
            Dim Key() As Byte = Guid.NewGuid().ToByteArray()
            Dim token As String
            If isusrnmright = True And iscstmIDright = True And isemailright = True AndAlso String.IsNullOrEmpty(theUserID) = False Then
                Try
                    token = VERAG_PROG_ALLGEMEIN.cCryptography3.Encrypt(Convert.ToBase64String(time.Concat(Key).ToArray()))
                    Return token
                Catch Ex As Exception
                    'Dim Msg, Style, Title As String
                    'Msg = "Token Generation failed" & vbCrLf & "A new E-mail has been sent to the intern e-mail given."
                    'Style = vbRetry + vbExclamation + vbDefaultButton1
                    'Title = "Error05: Token-Generierung"
                    'MsgBox(Msg, Style, Title)
                    'If MsgBox(Msg, Style, Title).Retry Then
                    'genToken(username, password, email)
                    token = VERAG_PROG_ALLGEMEIN.cCryptography3.Encrypt(Convert.ToBase64String(time.Concat(Key).ToArray()))
                    If SendEmail(username, password, email, token, CustomerID, isusrnmright, iscstmIDright, isemailright, Session.IsNewSession, theUserID) = True Then
                        'MsgBox("Email could not been sent because of an internal encryption error.", vbOK + vbInformation + vbDefaultButton1, "Token-Generation Error")
                    Else
                        'MsgBox("Email has been sent successful." & vbCr & "Please check your E-Mails!", vbOK + vbInformation + vbDefaultButton1, "Token-Generation successful!")
                    End If
                    'Else
                    'MsgBox("Token-Generation has not been successful." & vbCrLf & "Please try again in five seconds!")
                    Dim jetzt As DateTime = DateTime.UtcNow
                    Dim wenn As DateTime = DateTime.UtcNow.AddSeconds(-5)

                    If jetzt < wenn Then
                        Return "NotYet"
                    Else
                        token = genToken(username, password, email, CustomerID, isusrnmright, iscstmIDright, isemailright, Session.IsNewSession, theUserID)
                        Return token
                        'End If
                    End If
                End Try
            Else
                Return String.Empty
            End If
        Else
            Return "Error in Session ID. It has changed. Please check admin!"
        End If
    End Function

    Public Function RandomInteger(ByVal min As Integer, ByVal _
    max As Integer) As Integer
        Dim rand As New RNGCryptoServiceProvider()
        Dim one_byte() As Byte = {0}
        rand.GetBytes(one_byte)
        Return min + (max - min) * (one_byte(0) / 255)
    End Function

    Async Function gensaltToken(username As String, password As String, email As String, CustomerID As String, isusrnmright As Boolean, iscstmIDright As Boolean, isemailright As Boolean, isnewSession As Boolean, theUserID As String) As Task(Of String)
        If isnewSession = False Then
            Dim time() As Byte = BitConverter.GetBytes(DateTime.UtcNow.ToBinary())
            Dim Key() As Byte = Guid.NewGuid().ToByteArray()
            Dim token As Byte()

            Dim intzahl = RandomInteger(Math.Pow(2, 7), Math.Pow(2, 14))
            Dim intzahl2 = RandomInteger(Math.Pow(2, 7), Math.Pow(2, 10))
            Dim intzahliterats = RandomInteger(Math.Pow(2, 5), Math.Pow(2, 10))
            Dim Rand As Random = New Random
            If isusrnmright = True And iscstmIDright = True And isemailright = True AndAlso String.IsNullOrEmpty(theUserID) = False Then

                Dim salt As Byte() = VERAG_VARIABLES.GenerateSalt(intzahl)
                    'Dim tok As Byte = Convert.ToBase64String(time.Concat(Key).ToArray())
                    Dim tok As String = Convert.ToBase64String(time.Concat(Key).ToArray())
                    token = Await VERAG_VARIABLES.HashPassword(tok, salt, intzahliterats, intzahl)

                Return Convert.ToBase64String(token)
            Else
                Return String.Empty
            End If
        Else
            Return "Error in Session ID. It has changed. Please check admin!"
        End If
    End Function
    Function getDateoftoken(tokenname As String) As Boolean
        Dim data() As Byte = Convert.FromBase64String(VERAG_PROG_ALLGEMEIN.cCryptography3.Decrypt(tokenname))
        Dim wenn As DateTime = DateTime.FromBinary(BitConverter.ToInt64(data, 0))
        Dim nameoftoken = VERAG_PROG_ALLGEMEIN.cCryptography3.Decrypt(tokenname)
        If wenn < DateTime.UtcNow.AddMinutes(-30) Then
            nameoftoken = String.Empty
            tokenname = nameoftoken
            'MsgBox("Token has not been found or is too old!" + Environment.NewLine + "Please send a new E-mail!")
            If String.IsNullOrEmpty(txtEmail.Text) And String.IsNullOrEmpty(txt_CustomerID.Text) And String.IsNullOrEmpty(txt_Username.Text) Then
                lblMessage.Text = "Token has not been found or is too old!" + Environment.NewLine + "Please send a new E-mail!"
            ElseIf String.IsNullOrEmpty(txtEmail_M.Text) And String.IsNullOrEmpty(txt_CustomerID_M.Text) And String.IsNullOrEmpty(txt_Username_M.Text) Then
                lblMessage_M.Text = "Token has not been found or is too old!" + Environment.NewLine + "Please send a new E-mail!"
            End If
            Session.Remove("TokenforEmail")
            Return True
        ElseIf nameoftoken = "Error04" Then
            nameoftoken = String.Empty
            tokenname = nameoftoken
            Session.Remove("TokenforEmail")
            Return True
        ElseIf nameoftoken = "NotYet" Then
            Return True
        ElseIf nameoftoken = "Error in Session ID. It has changed. Please check admin!" Then
            ' Dim mailto As String = "support@verag.ag"
            Dim mailto As String = "ja@verag.ag"
            Dim htmlbody As String = String.Empty
            VERAG_VARIABLES.seterrorcount(500)
            Dim Betreff As String = "Session ID" + VERAG_VARIABLES.geterrornumb
            If String.IsNullOrEmpty(txt_Username.Text) = False And String.IsNullOrEmpty(txt_Username_M.Text) = True Then
                htmlbody = "<p> Der User " + txt_Username.Text + "hat eine ungültige oder geänderte Session-ID </p> <table><th><td>User</td></th><th><td>neue ID</td></th><tr><td>" + txt_Username.Text + "</td><td>" + Session.SessionID + "</td></tr></table>"
            ElseIf String.IsNullOrEmpty(txt_Username_M.Text) = False And String.IsNullOrEmpty(txt_Username.Text) = True Then
                htmlbody = "<p> Der User " + txt_Username_M.Text + "hat eine ungültige oder geänderte Session-ID </p> <table><th><td>User</td></th><th><td>neue ID</td></th><tr><td>" + txt_Username_M.Text + "</td><td>" + Session.SessionID + "</td></tr></table>"
            End If
            VERAG_PROG_ALLGEMEIN.cProgramFunctions.sendMail(mailto, Betreff, htmlbody)
            Return False
        Else
            Return True
        End If
    End Function

    Function RandomString(r As Random, max As Integer) As String
        Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!§$%&/?="
        Dim sb As New StringBuilder
        Dim cnt As Integer = r.Next(4, max)
        For i As Integer = 1 To cnt
            Dim idx As Integer = r.Next(0, s.Length)
            sb.Append(s.Substring(idx, 1))
        Next
        Return sb.ToString()
    End Function

    Protected Async Sub btn_Testmail_Click(sender As Object, e As EventArgs)
        Dim username As String = "userwithlongername"
        Dim Passw As String = "Test1!W"
        Dim email As String = "ja@verag.ag"
        Dim CustomerID As String = "717585"
        Dim TheusrID As String = "3"
        Dim tokentest As String = genToken(username, Passw, email, CustomerID, True, True, True, False, TheusrID)
        Dim hashtoken As Byte()
        Dim iterationnumb As Integer = VERAG_VARIABLES.getiterationnumber
        Dim nzahl As Integer = RandomInteger(Math.Pow(2, 7), Math.Pow(2, 10))
        'Dim salttoken As String = gensaltToken(username, Passw, email, CustomerID, True, True, True, False, TheusrID)
        'MsgBox(salttoken)
        If Session.Item("TokenforEmail") = Nothing Then
            tokentest = genToken(username, Passw, email, CustomerID, True, True, True, False, TheusrID)
            Session.Add("TokenforEmail", tokentest)
            Session.Add("SessID", VERAG_PROG_ALLGEMEIN.cCryptography.Encrypt(Session.SessionID))
        Else
            tokentest = Session.Item("TokenforEmail")
        End If
        hashtoken = Await VERAG_VARIABLES.HashPassword(tokentest, salt, iterationnumb, nzahl)
        If Await VERAG_VARIABLES.Verifyhash(tokentest, salt, hashtoken, iterationnumb, nzahl) = True Then
            If SendEmail(username, Passw, email, tokentest, CustomerID, True, True, True, False, TheusrID) = True Then
                'password = RandomString(New Random, 10)
                If getDateoftoken(tokentest) = True Then
                    'Dim msgboxstyle = vbDefaultButton1 + vbOK
                    'MsgBox(tokenname, msgboxstyle)
                    lblMessage_M.ForeColor = Color.Green
                    lblMessage_M.Text = "Token generated successfully."
                    'MsgBox("Token generated successfully.")
                Else
                    lblMessage_M.ForeColor = Color.Red
                    VERAG_VARIABLES.seterrorcount(100)
                    lblMessage_M.Text = VERAG_VARIABLES.geterrornumb + "Token is not valid anymore. Please generate a new one by sending a new e-mail!"
                    'MsgBox("Token is not valid anymore. Please generate a new one by sending a new e-mail!")

                    If Session.Item("TokenforEmail") = Nothing Then
                        tokentest = genToken(username, Passw, email, CustomerID, True, True, True, False, TheusrID)
                        Session.Add("TokenforEmail", tokentest)
                    Else
                        tokentest = Session.Item("TokenforEmail")
                    End If
                End If
            Else
            End If
            'SendEmail(username, password, email)
            'MsgBox("Mail would be sent successfully!")
            lblMessage_M.ForeColor = Color.Green
            lblMessage_M.Text = "The password has been sent sucessfully on the given valid e-mail address."
        End If
    End Sub
End Class