SCGUI.ps1


<#PSScriptInfo
 
.VERSION 1.0
 
.GUID 57690308-2ec1-4bbe-992f-9393da012e5f
 
.AUTHOR zackary.divine@gmail.com
 
.COMPANYNAME DeveloperDivine
 
.COPYRIGHT Zackary Divine (C)
 
.TAGS Exchange,Office365,GUI
 
.LICENSEURI
 
.PROJECTURI
 
.ICONURI
 
.EXTERNALMODULEDEPENDENCIES
 
.REQUIREDSCRIPTS
 
.EXTERNALSCRIPTDEPENDENCIES
 
.RELEASENOTES
 
 
#>


<#
 
.DESCRIPTION
 Manages basic operations in office 365 and local exchange. Initally the program starts with a setup of the ADGroups who are going to be admins and users. The users in the groups are allowed to use the program. This program will then allow the user to create / modify Distribution groups security groups and will allow the removal of users from office 365 block lists.
 
#>
 
#region Import the Assemblies
[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
[reflection.assembly]::LoadWithPartialName("System.Windows") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
[void][Windows.Security.Credentials.PasswordVault,Windows.Security.Crentials,ContentType=WindowsRuntime]
Add-Type -AssemblyName PresentationCore,PresentationFramework
Import-Module ActiveDirectory
#endregion

$directory = "$($env:USERPROFILE)\SCGUI"
$configFile = "$($directory)\assets\security\config.xml"
$keyFile = "$($directory)\assets\security\key.key"
$exportDirectory = "$directory\Exports"
$SettingsFile = "C:\ProgramData\SCGUI\Settings.xml"

$notifyIcon = New-Object System.Windows.Forms.NotifyIcon
$notifyIcon.Icon = 'C:\Program Files\Common Files\server_earth_aTu_icon.ico'
$notifyIcon.Visible = $True
$loginForm = New-Object System.Windows.Forms.Form
$vault = New-Object Windows.Security.Credentials.PasswordVault
$key = "HKLM:\SOFTWARE"


function set-Connected($bool)
{
    [Environment]::SetEnvironmentVariable("Connected", $bool)
}
function set-ConnectedID($id)
{
    [Environment]::SetEnvironmentVariable("ConnectedId", "$id")
}
function set-ConnectedServerType($type)
{
    [Environment]::SetEnvironmentVariable("ConnectedServerType", $type)
}
function set-ConnectedUser($user)
{
    [Environment]::SetEnvironmentVariable("ConnectedUser", $user)
}
function set-SessionID($id)
{
    [Environment]::SetEnvironmentVariable("sessionID", $id)
}
function set-isOWAConnected($value)
{
    [Environment]::SetEnvironmentVariable("isOWAConnected", $value)
}
function set-isLocalConnected($value)
{
    [Environment]::SetEnvironmentVariable("isLocalConnected", $value)
}

#region Settings Region
function setLocalExchangeAddress($value)
{
    [Environment]::SetEnvironmentVariable("LocalServerAddress", $value)
}
function setDomain($value)
{
    [Environment]::SetEnvironmentVariable("Domain", $value)
}
function setADAdminGroup($group)
{
    [Environment]::SetEnvironmentVariable("AdminGroup", $group)
}
function setADUsersGroup($group)
{
    [Environment]::SetEnvironmentVariable("UsersGroup", $group)
}
function setSessionLogLocation($location)
{
    [Environment]::SetEnvironmentVariable("sessionLogLocation", $location)
}

function Load_Settings([System.Windows.Forms.DataGridView] $propertyGrid)
{
    [xml] $settingsDocument = Get-Content $SettingsFile
    if ($settingsDocument.SelectNodes("//Setting"))
    {
        foreach ($setting in $settingsDocument.SelectNodes("//Setting"))
        {
            if ($setting.Domain)
            {
                if ($propertyGrid)
                {
                    $propertyGrid.Rows[0].Cells[1].Value = $setting.Domain
                }
                setDomain -value "$($setting.Domain)"
            }
            if ($setting.LocalExchangeAddress)
            {
                if ($propertyGrid)
                {
                    $propertyGrid.Rows[1].Cells[1].Value = $setting.LocalExchangeAddress
                }
                setLocalExchangeAddress -value "$($setting.LocalExchangeAddress)"
            }
            if ($setting.LogLocation)
            {
                if ($propertyGrid)
                {
                    $propertyGrid.Rows[2].Cells[1].Value = $setting.LogLocation
                }
                setSessionLogLocation -location "$($setting.LogLocation)"
            }
            if ($setting.AdminGroup)
            {
                if ($propertyGrid)
                {
                    $propertyGrid.Rows[3].Cells[1].Value = $setting.AdminGroup
                }
                setADAdminGroup -group "$($setting.AdminGroup)"
            }
            if ($setting.UsersGroup)
            {
                if ($propertyGrid)
                {
                    $propertyGrid.Rows[4].Cells[1].Value = $setting.UsersGroup
                }
                setADUsersGroup -group "$($setting.UsersGroup)"
            }
        }
    }
}
function Modify_Settings($settingObject, $value)
{
    [xml] $settingsDocument = Get-Content $SettingsFile
    if ($settingsDocument.SelectNodes("//Setting"))
    {
        foreach ($setting in $settingsDocument.SelectNodes("//Setting"))
        {
            if ($settingObject -eq "Domain")
            {
                $setting.Domain = "$value"
            }
            if ($settingObject -eq "Local Exchange Address")
            {
                $setting.LocalExchangeAddress = "$value"
            }
            if ($settingObject -eq "Log Location")
            {
                Copy-Item $setting.LogLocation -Destination "$($value)"
                $setting.LogLocation = "$value"
            }
            if ($settingObject -eq "Admin Group")
            {
                $setting.AdminGroup = "$value"
            }
            if ($settingObject -eq "Users Group")
            {
                $setting.UsersGroup = "$value"
            }
        }
    }
    save-settingsLog -log $settingsDocument
    Load_Settings

}
#endregion


$env:Connected = "false"
$env:ConnectedId = 0
$env:ConnectedServerType = ""
$env:ConnectedUser = ""
$env:LocalServerAddress = ""
$env:sessionLogLocation = ""
$env:Domain = ""
$env:AdminGroup = ""
$env:UsersGroup = ""
$env:sessionID = ''

$env:isOWAConnected = 'NO'
$env:isLocalConnected = 'NO'
$env:version = "1.4"


function get-File () {

    $openFile = New-Object System.Windows.Forms.OpenFileDialog
    $openFile.InitialDirectory = "$($env:USERPROFILE)\Desktop"
    $openFile.Filter = "CSV (*.csv)|*.csv| XML (*.xml)|*.xml"
    $openFile.ShowDialog() | Out-Null
    $openFile.Multiselect = $false
    
    return $openFile.FileName
}

#Generated Form Function
function GenerateForm (<#$server#>) {
    ########################################################################
    # Code Generated By: SAPIEN Technologies PrimalForms (Community Edition) v1.0.10.0
    # Generated On: 4/10/2013 2:07 PM
    # Generated By: Austin Heyne
    ########################################################################
    ########################################################################
    # Modified By: Zackary Divine
    # Last Updated On: 5/17/2017 1:44PM
    # Disclaimer "Use at own risk. This software is capable of deleting groups, mailboxes, etc.."
    ########################################################################
    #region Generated Form Objects
    $form1 = New-Object System.Windows.Forms.Form
    $InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
    $tabControl1 = New-Object System.Windows.Forms.TabControl


    #Tab1 Only on Local Exchange
    $tabPageDL = New-Object System.Windows.Forms.TabPage
    $groupBox2 = New-Object System.Windows.Forms.GroupBox
    $CB_Sponsors = New-Object System.Windows.Forms.CheckBox
    $RTB_Members = New-Object System.Windows.Forms.RichTextBox
    $label4 = New-Object System.Windows.Forms.Label
    $RTB_DLOutput = New-Object System.Windows.Forms.RichTextBox
    $Create = New-Object System.Windows.Forms.Button
    $ListInGAL = New-Object System.Windows.Forms.CheckBox
    $groupBox1 = New-Object System.Windows.Forms.GroupBox
    $RB_IO = New-Object System.Windows.Forms.RadioButton
    $RB_OO = New-Object System.Windows.Forms.RadioButton
    $RB_MO = New-Object System.Windows.Forms.RadioButton
    $RB_A = New-Object System.Windows.Forms.RadioButton
    $TB_EmailAddress = New-Object System.Windows.Forms.TextBox
    $label3 = New-Object System.Windows.Forms.Label
    $TB_Sponsors = New-Object System.Windows.Forms.TextBox
    $label2 = New-Object System.Windows.Forms.Label
    $TB_Alias = New-Object System.Windows.Forms.TextBox
    $UseCustomAlias = New-Object System.Windows.Forms.CheckBox
    $TB_DGN = New-Object System.Windows.Forms.TextBox
    $label1 = New-Object System.Windows.Forms.Label
    $uploadDLMembers = New-Object System.Windows.Forms.ContextMenuStrip
    $uploadCsv = New-Object System.Windows.Forms.ToolStripMenuItem
    $uploadSponsers = New-Object System.Windows.Forms.ContextMenuStrip
    $uploadSponsersCSV = New-Object System.Windows.Forms.ToolStripMenuItem
    $GB_DLType = New-Object System.Windows.Forms.GroupBox
    $RB_SecurityGroup = New-Object System.Windows.Forms.RadioButton
    $RB_DistributionGroup = New-Object System.Windows.Forms.RadioButton

    #Tab2
    $tabPageIQ = New-Object System.Windows.Forms.TabPage
    $B_SetCustom = New-Object System.Windows.Forms.Button
    $label_IQ_12 = New-Object System.Windows.Forms.Label
    $TB_ProhibitSend = New-Object System.Windows.Forms.TextBox
    $label_IQ_11 = New-Object System.Windows.Forms.Label
    $label_IQ_10 = New-Object System.Windows.Forms.Label
    $TB_IssueWarning = New-Object System.Windows.Forms.TextBox
    $label_IQ_9 = New-Object System.Windows.Forms.Label
    $B_IQ_SetDefault = New-Object System.Windows.Forms.Button
    $label_IQ_Out = New-Object System.Windows.Forms.Label
    $B_IQ_Check = New-Object System.Windows.Forms.Button
    $TB_IQName = New-Object System.Windows.Forms.TextBox
    $label_IQ_7 = New-Object System.Windows.Forms.Label

    #Tab3
    $tabPageMBP = New-Object System.Windows.Forms.TabPage

    $TargetEmail_GB = New-Object System.Windows.Forms.GroupBox
    $TB_MBP_Target = New-Object System.Windows.Forms.TextBox

    $properties_GB = New-Object System.Windows.Forms.GroupBox
    $CB_MBP_FullAccess = New-Object System.Windows.Forms.CheckBox
    $CB_MBP_SendAs = New-Object System.Windows.Forms.CheckBox
    $TB_MBP_User = New-Object System.Windows.Forms.TextBox

    $otherSettings_GB = New-Object System.Windows.Forms.GroupBox
    $CB_MBP_SendSize = New-Object System.Windows.Forms.CheckBox
    $TB_SendSize = New-Object System.Windows.Forms.TextBox
    $LB_SendSizeType = New-Object System.Windows.Forms.Label
    $CB_MBP_ReceiveSize = New-Object System.Windows.Forms.CheckBox
    $TB_ReceiveSize = New-Object System.Windows.Forms.TextBox
    $LB_ReceiveSizeType = New-Object System.Windows.Forms.Label
    $HideGal = New-Object System.Windows.Forms.CheckBox

    $cGroupBox = New-Object System.Windows.Forms.GroupBox
    $RB_M = New-Object System.Windows.Forms.RadioButton
    $RB_S = New-Object System.Windows.Forms.RadioButton
    $RB_R = New-Object System.Windows.Forms.RadioButton

    $RTB_MBP_Output = New-Object System.Windows.Forms.RichTextBox
    $B_MBP_Set = New-Object System.Windows.Forms.Button

    #CMSTab for ou main page
    $CMS_Tab = New-Object System.Windows.Forms.TabPage
    $CMS_Progress = New-Object System.Windows.Forms.ProgressBar
    $CMS_Status = New-Object System.Windows.Forms.Label
    $CMS_Members = New-Object System.Windows.Forms.RichTextBox
    $CMS_Context_CMS = New-Object System.Windows.Forms.ContextMenuStrip
    $uploadCSV_CMS = New-Object System.Windows.Forms.ToolStripMenuItem
    $CMS_label3 = New-Object System.Windows.Forms.Label
    $CMS_Create = New-Object System.Windows.Forms.Button
    $CMS_Owners = New-Object System.Windows.Forms.TextBox
    $CMS_label2 = New-Object System.Windows.Forms.Label
    $CMS_label1 = New-Object System.Windows.Forms.Label
    $CMS_Group = New-Object System.Windows.Forms.TextBox

    #Tab4
    $tabPageConsole = New-Object System.Windows.Forms.TabPage
    $RTB_Console = New-Object System.Windows.Forms.RichTextBox

    #OWA - Unblock
    $tabPageOWAUnBlock = New-Object System.Windows.Forms.TabPage
    $GB_UsersUnblock = New-Object System.Windows.Forms.GroupBox
    $GB_BlockedUsers = New-Object System.Windows.Forms.GroupBox
    $RTB_UsersToUnblock = New-Object System.Windows.Forms.RichTextBox
    $DGV_BlockedUsers = New-Object System.Windows.Forms.DataGridView
    $UnblockButton = New-Object System.Windows.Forms.Button
    $OWAUnblockContext = New-Object System.Windows.Forms.ContextMenuStrip
    $OWAUserUnblock = New-Object System.Windows.Forms.ToolStripMenuItem
    $OWASearchBlock = New-Object System.Windows.Forms.ToolStripMenuItem

    #region Group Membership Tab
    $membershipTab = New-Object System.Windows.Forms.TabPage
    $uploadMembersMenu = New-Object System.Windows.Forms.ContextMenuStrip
    $uploadMembers = New-Object System.Windows.Forms.ToolStripMenuItem
    $GB_DL_SG = New-Object System.Windows.Forms.GroupBox
    $GB_Members = New-Object System.Windows.Forms.GroupBox
    $GB_Methods = New-Object System.Windows.Forms.GroupBox
    $GB_SetGetMethods = New-Object System.Windows.Forms.GroupBox
    $GB_ExportOptions = New-Object System.Windows.Forms.GroupBox
    $GB_CurrentMembers = New-Object System.Windows.Forms.GroupBox
    $GB_MembershipErrors = New-Object System.Windows.Forms.GroupBox
    $TB_DLSG_Name = New-Object System.Windows.Forms.TextBox
    $RTB_GroupMembership = New-Object System.Windows.Forms.RichTextBox
    $DGV_CurrentMembers = New-Object System.Windows.Forms.DataGridView
    $RTB_MembershipErrors = New-Object System.Windows.Forms.RichTextBox
    $RB_AddMethod = New-Object System.Windows.Forms.RadioButton
    $RB_RemoveMethod = New-Object System.Windows.Forms.RadioButton
    $RB_ReplaceMethod = New-Object System.Windows.Forms.RadioButton
    $RB_GetMethod = New-Object System.Windows.Forms.RadioButton
    $RB_SetMethod = New-Object System.Windows.Forms.RadioButton
    $CB_CSVOption = New-Object System.Windows.Forms.CheckBox
    $CB_XML = New-Object System.Windows.Forms.Checkbox
    $BN_SetRetrieveMembership = New-Object System.Windows.Forms.Button
    #add another depending on needed items

    #endregion


    #endregion Generated Form Objects

    #----------------------------------------------
    #Generated Event Script Blocks
    #----------------------------------------------
    #Provide Custom Code for events specified in PrimalForms.

    #region Create DL
    $Create_OnClick= 
    {    
        #Clear any text from DLOutput
        $RTB_DLOutput.Text = ""
        . updateDLOutput
        $RTB_DLOutput.AppendText("Creating DL...")
    
        #Handleing Generated Alias or Custom Alias
        if($UseCustomAlias.Checked){$alias = $TB_Alias.Text}
        else{$alias = $TB_DGN.Text.Replace(" ","").Replace("(","").Replace(")","").Replace(",","").Replace("*","").Replace("$","").Replace("!","").Replace("#","").Replace("%","").Replace("^","").Replace("+","").Replace('`',"").Replace("~","").Replace("<","").Replace(">","").Replace("'","")}
        $RTB_DLOutput.AppendText("`nDGN: " + $TB_DGN.Text)
        $RTB_DLOutput.AppendText("`nAlias: " + $alias.toString())
        . updateDLOutput
    
        #Handle Sponsor Check
        $sponsorList = $TB_Sponsors.Text.Split(",")
        if(!$?){
            $RTB_DLOutput.AppendText("`nError Checking Sponsor List")
            . updateDLOutput 
        }else{
            $RTB_DLOutput.AppendText("`nSponsors Approved")
            . updateDLOutput
        }

        #Create SEcurity Group if either security group option is checked
        if($RB_SecurityGroup.Checked)
        {
            $createSecurityGroupAction = add-ActionElementToSessionLog -action "Create SecurityGroup"
            #uncomment if correct way to create a security Group
            #region Create Security Group Testing
            try {
                New-LocalDistributionGroup -Alias $alias -Name $TB_DGN.Text -Type Security -OrganizationalUnit OU="Groups,OU=DLs,OU=Exchange,dc=sooner,dc=net,dc=ou,dc=edu" -ManagedBy $sponsorList -SamAccountName $alias | Out-String -Stream | ForEach-Object{
                $RTB_Console.AppendText("`n" + $_)
                . updateConsole}
                add-actionDetails -detailTitle "Security Group Created" -detailExplanation "The security group: $($alias) has been created." -actionElement $createSecurityGroupAction
            } catch
            {
                add-actionDetails -detailTitle "Error Creating Security Group" -detailExplanation "We ran into an error when trying to create the security group" -errorcode "401" -actionElement $createSecurityGroupAction
            }


            #Modify Email Address Policy
            try {
                Set-LocalDistributionGroup $TB_DGN.Text -EmailAddressPolicyEnabled $false | Out-String | ForEach-Object{
                $RTB_Console.AppendText("`n" + $_)
                . updateConsole}

                add-actionDetails -detailTitle "Distribution Group Email Policy" -detailExplanation "False" -actionElement $createSecurityGroupAction
            } catch
            {
                add-actionDetails -detailTitle "Distribution Group Email Policy" -detailExplanation "An Error occured when setting the group policy. No changes were made." -errorcode "401" -actionElement $createSecurityGroupAction
            }
        
            #Add Default Email Address
            $emailAddresses = $(Get-LocalDistributionGroup $TB_DGN.Text).EmailAddresses
            $newAddress = "SMTP:" + $alias + "@sooner.net.ou.edu"
            $emailAddresses += $newAddress

            Set-LocalDistributionGroup $TB_DGN.Text -EmailAddresses $emailAddresses  | Out-String | ForEach-Object{
                $RTB_Console.AppendText("`n" + $_)
                . updateConsole}
            foreach($_ in $emailAddresses){
                $RTB_DLOutput.AppendText("`n" + $_)
                . updateDLOutput
            
                add-actionDetails -detailTitle "Set Distribution Group EmailAddress" -detailExplanation "$($_)" -actionElement $createSecurityGroupAction
            }
            #TODO Need to add primary smtp address to @ou.edu email address
            #Add @ou.edu Email Address
            if($TB_EmailAddress.Text.Replace(" ","") -ne "")
            {
                $newAddress = "SMTP:" + $TB_EmailAddress.Text + "@ou.edu"
                $emailAddresses += $newAddress
                Set-LocalDistributionGroup $TB_DGN.Text -EmailAddresses $emailAddresses | Out-String |ForEach-Object{
                    $RTB_Console.AppendText("`n" + $_)
                    . updateConsole
                }
                
                if(!$?){
                    $RTB_DLOutput.AppendText("`nError adding @ou.edu address, See Console")
                    . updateDLOutput

                    add-actionDetails -detailTitle "Error" -detailExplanation "Error in creating the @ou.edu email address" -errorcode "402" -actionElement $createSecurityGroupAction
                }
                else{
                    $RTB_DLOutput.AppendText("`nAdded " + $newAddress)
                    . updateDLOutput

                    add-actionDetails -detailTitle "Create @ou.edu Email Address" -detailExplanation "$($newAddress)" -actionElement $createSecurityGroupAction
                }        
            }
            else
            {
                $newAddress = "SMTP:" + $alias + "@ou.edu"
                $emailAddresses += $newAddress

                try{
                    Set-LocalDistributionGroup $TB_DGN.Text -EmailAddresses $emailAddresses | Out-String | ForEach-Object{
                        $RTB_Console.AppendText("`n" + $_)
                        . updateDLOutput

                        add-actionDetails -detailTitle "Create @ou.edu Email Address" -detailExplanation "$($newAddress)" -actionElement $createSecurityGroupAction
                    }
                } catch
                {
                    add-actionDetails -detailTitle "Error Creating @ou EmailAddress" -detailExplanation "$($newAddress)"-errorcode "401" -actionElement $createSecurityGroupAction
                }
            }

            #Handle list membership
            if($CB_Sponsors.Checked){
                $sponsorList | foreach {Add-LocalDistributionGroupMember -Identity $TB_DGN.Text -Member $_; add-actionDetails -detailTitle "Add Sponsers As Members to DistributionGroup" -detailExplanation "Member Added: $_" -actionElement $createSecurityGroupAction}
                $RTB_DLOutput.AppendText("`nSponsors added to DL")
                . updateDLOutput
            }
            if($RTB_Members.Text -ne ""){
                $memberList = $RTB_Members.Text.Split("`n")
                $memberList | foreach {Add-LocalDistributionGroupMember -Identity $TB_DGN.Text -Member $_; add-actionDetails -detailTitle "AddDistributionGroupMember" -detailExplanation "Member has been Added: $_" -actionElement $createSecurityGroupAction}
                $RTB_DLOutput.AppendText("`nMembers added to DL")
                . updateDLOutput
            }

            # TODO LIST IN GAL IS BROKEN

            #List in GAL?
            

            if($ListInGAL.Checked){
                Set-LocalDistributionGroup $TB_DGN.Text -HiddenFromAddressListsEnabled $false

                add-actionDetails -detailTitle "Hidden From GAL" -detailExplanation "False" -actionElement $createSecurityGroupAction
            }else{
                Set-LocalDistributionGroup $TB_DGN.Text -HiddenFromAddressListsEnabled $true

                add-actionDetails -detailTitle "Hidden From GAL" -detailExplanation "True" -actionElement $createSecurityGroupAction
            }

            #endregion
            #Clear Form
            $TB_Alias.Text = ""
            $TB_DGN.Text = ""
            $TB_EmailAddress.Text = ""
            $TB_Sponsors.Text = ""
            $UseCustomAlias.Checked = $false
            $RB_A.Checked = $true
            $RTB_Members.Text = ""
            save-actionElementToSessionLog -element $createSecurityGroupAction
            save-sessionLog -log $sessionLog -element $sessionElement
            return
        }

        $createDLAction = add-ActionElementToSessionLog -action "CreateDistributionGroup"
    
        #Create DL
        New-LocalDistributionGroup -Alias $alias -Name $TB_DGN.Text -Type Distribution -OrganizationalUnit OU="DLs,OU=Exchange,dc=sooner,dc=net,dc=ou,dc=edu" -ManagedBy $sponsorList -SamAccountName $alias  | Out-String -Stream | ForEach-Object {
            $RTB_Console.AppendText("`n" + $_)
            . updateConsole}
        if(!$?){
            $RTB_DLOutput.AppendText("`nError Creating DL, See Console")
            . updateDLOutput
            add-actionDetails -detailTitle "DistributionGroupError" -detailExplanation "An error occured in create the DL" -errorcode "400" -actionElement $createDLAction
            break
        }else{
            $RTB_DLOutput.AppendText("`nDL Created, See Console for more information")
            . updateDLOutput

            add-actionDetails -detailTitle "Distribution Group Alias" -detailExplanation "$($alias)" -actionElement $createDLAction
        }
    
        #Modify Email Address Policy
        try {
            Set-LocalDistributionGroup $TB_DGN.Text -EmailAddressPolicyEnabled $false | Out-String | ForEach-Object{
            $RTB_Console.AppendText("`n" + $_)
            . updateConsole}

            add-actionDetails -detailTitle "Distribution Group Email Policy" -detailExplanation "False" -actionElement $createDLAction
        } catch
        {
            add-actionDetails -detailTitle "Distribution Group Email Policy" -detailExplanation "An Error occured when setting the group policy. No changes were made." -errorcode "401" -actionElement $createDLAction
        }


        
        #Add Default Email Address
        $emailAddresses = $(Get-LocalDistributionGroup $TB_DGN.Text).EmailAddresses
        $newAddress = "SMTP:" + $alias + "@sooner.net.ou.edu"
        $emailAddresses += $newAddress

        Set-LocalDistributionGroup $TB_DGN.Text -EmailAddresses $emailAddresses  | Out-String | ForEach-Object{
            $RTB_Console.AppendText("`n" + $_)
            . updateConsole}
        foreach($_ in $emailAddresses){
            $RTB_DLOutput.AppendText("`n" + $_)
            . updateDLOutput
            
            add-actionDetails -detailTitle "Set Distribution Group EmailAddress" -detailExplanation "$($_)" -actionElement $createDLAction
        }
    
        #Add @ou.edu Email Address
        if($TB_EmailAddress.Text.Replace(" ","") -ne "")
        {
            $newAddress = "SMTP:" + $TB_EmailAddress.Text + "@ou.edu"
            $emailAddresses += $newAddress
            Set-LocalDistributionGroup $TB_DGN.Text -EmailAddresses $emailAddresses | Out-String |ForEach-Object{
                $RTB_Console.AppendText("`n" + $_)
                . updateConsole
            }
            if(!$?){
                $RTB_DLOutput.AppendText("`nError adding @ou.edu address, See Console")
                . updateDLOutput

                add-actionDetails -detailTitle "Error" -detailExplanation "Error in creating the @ou.edu email address" -errorcode "402" -actionElement $createDLAction
            }else{
                $RTB_DLOutput.AppendText("`nAdded " + $newAddress)
                . updateDLOutput

                add-actionDetails -detailTitle "Create @ou.edu Email Address" -detailExplanation "$($newAddress)" -actionElement $createDLAction
            }        
        } 
        else
        {
            $newAddress = "SMTP:" + $alias + "@ou.edu"
            $emailAddresses += $newAddress

            Set-LocalDistributionGroup $TB_DGN.Text -EmailAddresses $emailAddresses | Out-String |ForEach-Object{
                $RTB_Console.AppendText("`n" + $_)
                . updateConsole

            if(!$?){
                $RTB_DLOutput.AppendText("`nError adding @ou.edu address, See Console")
                . updateDLOutput

                add-actionDetails -detailTitle "Error" -detailExplanation "Error in creating the @ou.edu email address" -errorcode "402" -actionElement $createDLAction
            }else{
                $RTB_DLOutput.AppendText("`nAdded " + $newAddress)
                . updateDLOutput

                add-actionDetails -detailTitle "Create @ou.edu Email Address" -detailExplanation "$($newAddress)" -actionElement $createDLAction
            }    
        }
    
        #List in GAL?
        if($ListInGAL.Checked){
            Set-LocalDistributionGroup $TB_DGN.Text -HiddenFromAddressListsEnabled $false

            add-actionDetails -detailTitle "Hidden From GAL" -detailExplanation "False" -actionElement $createDLAction
        }else{
            Set-LocalDistributionGroup $TB_DGN.Text -HiddenFromAddressListsEnabled $true

            add-actionDetails -detailTitle "Hidden From GAL" -detailExplanation "True" -actionElement $createDLAction
        }
    
        #Handle who can send to list
        if($RB_A.Checked)
        {
            Set-LocalDistributionGroup $TB_DGN.Text -RequireSenderAuthenticationEnabled $false
        
            add-actionDetails -detailTitle "RequireSenderAuthenticationEnabled" -detailExplanation "False" -actionElement $createDLAction
        }
        if($RB_MO.Checked)
        {
            Set-LocalDistributionGroup $TB_DGN.Text -AcceptMessagesOnlyFromDLMembers $TB_DGN.Text

            add-actionDetails -detailTitle "AcceptMessagesOnlyFromDLMembers" -detailExplanation "$($TB_DGN.Text)" -actionElement $createDLAction
        }
        if($RB_OO.Checked)
        {
            #This creates another DL called $alias + "-group" that is used as the group that can send to DL
            try {
                
                New-LocalDistributionGroup -Alias ($alias + "-group") -Name ($alias + "-group") -Type Security -OrganizationalUnit  OU="DLs,OU=Exchange,dc=sooner,dc=net,dc=ou,dc=edu" -SamAccountName ($alias + "-group") 

                add-actionDetails -detailTitle "Create Security Group" -detailExplanation "Created a secruity group that can send to created group. SecurityGroupName: $alias-group" -actionElement $createDLAction
            } catch
            {
                add-actionDetails -detailTitle "Error" -detailExplanation "Failed to create the secruity group." -errorcode "401" -actionElement $createDLAction
            }

            #Make universal group
            Set-ADGroup -Identity ($alias + "-group") -GroupScope Universal

            add-actionDetails -detailTitle "Set-ADGroup: $($alias)-group" -detailExplanation "GroupScope: Universal" -actionElement $createDLAction

            #Mail Enable group (May error out and silently continue from already being set)
            Enable-LocalDistributionGroup ($alias + "-group")

            add-actionDetails -detailTitle "EnabledDistributionGroup: $($alias)-group" -detailExplanation "Mail-Enable the secruity group" -actionElement $createDLAction

            #Wait for new DL to replicate
            $RTB_DLOutput.AppendText("`nPlease wait 60 seconds for Owners Group to replicate")
            . updateDLOutput

            Start-Sleep -Seconds 60

            Set-LocalDistributionGroup ($alias + "-group") -HiddenFromAddressListsEnabled $true

            add-actionDetails -detailTitle "Hide SecurityGroup from Address lists" -detailExplanation "True" -actionElement $createDLAction

            Set-LocalDistributionGroup ($alias + "-group") -AcceptMessagesOnlyFromDLMembers ($alias + "-group")

            add-actionDetails -detailTitle "SetSecurityGroup" -detailExplanation "Accept Messages Only From DL Members $($alias)-group" -actionElement $createDLAction

            $sponsorList | foreach {Add-DistributionGroupMember -Identity ($alias + "-group") -Member $_; add-actionDetails -detailTitle "Add Security Group Member" -detailExplanation "Added Member $_" -actionElement $createDLAction}

            Set-LocalDistributionGroup $TB_DGN.Text -AcceptMessagesOnlyFromDLMembers ($alias + "-group")

            add-actionDetails -detailTitle "Set Distribution Group" -detailExplanation "Accept Messages Only From DL Members $($alias)-group" -actionElement $createDLAction
        }
        if($RB_IO.Checked)
        {
            Set-LocalDistributionGroup $TB_DGN.Text -RequireSenderAuthenticationEnabled $true

            add-actionDetails -detailTitle "SetDistributionGroup" -detailExplanation "RequireSenderAuthenticationEnabled True" -actionElement $createDLAction
        }
    
        #Handle list membership
        if($CB_Sponsors.Checked){
            $sponsorList | foreach {Add-LocalDistributionGroupMember -Identity $TB_DGN.Text -Member $_; add-actionDetails -detailTitle "Add Sponsers As Members to DistributionGroup" -detailExplanation "Member Added: $_" -actionElement $createDLAction}
            $RTB_DLOutput.AppendText("`nSponsors added to DL")
            . updateDLOutput
        }
        if($RTB_Members.Text -ne ""){
            $memberList = $RTB_Members.Text.Split("`n")
            $memberList | foreach {Add-LocalDistributionGroupMember -Identity $TB_DGN.Text -Member $_; add-actionDetails -detailTitle "AddDistributionGroupMember" -detailExplanation "Member has been Added: $_" -actionElement $createDLAction}
            $RTB_DLOutput.AppendText("`nMembers added to DL")
            . updateDLOutput
        }
    
    
        $RTB_DLOutput.AppendText("`nDL Created, populate through ADUC")
        . updateDLOutput

        save-actionElementToSessionLog -element $createDLAction
        save-sessionLog -log $sessionLog -element $sessionElement

        #Clear Form
        $TB_Alias.Text = ""
        $TB_DGN.Text = ""
        $TB_EmailAddress.Text = ""
        $TB_Sponsors.Text = ""
        $UseCustomAlias.Checked = $false
        $RB_A.Checked = $true
        $RTB_Members.Text = ""
        }
    }
    #endregion Create DL

    #region Set MBPerms
    $B_MBP_Set_OnClick= 
    {
        $setMBAction = add-ActionElementToSessionLog -action "Setting Mailbox Permissions"

        $RTB_MBP_Output.AppendText("Starting...")
        . updateMBPOutput 
        #Check for input error
        if(($TB_MBP_Target.Text.Replace(" ","") -eq "") -and ($TB_MBP_Target.Text -notlike "*@ou.edu")){
            $RTB_MBP_Output.AppendText("`nMissing input data")
            . updateMBPOutput 
            add-actionDetails -detailTitle "Mailbox Not Found" -detailExplanation "($($TB_MBP_Target.Text)) Not Found" -actionElement $setMBAction
        } else{
            $MBP_Target = Get-OwaMailbox $TB_MBP_Target.Text
            $RTB_MBP_Output.AppendText("`nTarget: " + $MBP_Target.PrimarySMTPAddress)
            . updateMBPOutput

            if ($RB_S.Checked -or $RB_R.Checked)
            {
                $RB_S_CHECK = $RB_S.Checked
                $RB_R_CHECK = $RB_R.Checked
                if ($RB_S_CHECK)
                {
                    Set-OWAMailBox $TB_MBP_Target.Text -Type Shared -MessageCopyForSendOnBehalfEnabled $True -MessageCopyForSentAsEnabled $True
                    $RTB_MBP_Output.AppendText("`n Converting: " + $MBP_Target.PrimarySmtpAddress + " to Shared Mailbox")
                    . updateMBPOutput

                    add-actionDetails -detailTitle "Convert Mailbox" -detailExplanation "Type Shared: $($TB_MBP_Target.text)" -actionElement $setMBAction
                }
                if ($RB_R_CHECK)
                {
                    Set-OWAMailBox $TB_MBP_Target.Text -Type Room
                    $RTB_MBP_Output.AppendText("`n Converting: " + $MBP_Target.PrimarySmtpAddress + " to Room")
                    . updateMBPOutput

                    add-actionDetails -detailTitle "Convert Mailbox" -detailExplanation "Type Room: $($TB_MBP_Target.text) " -actionElement $setMBAction
                }
            }
            if (($TB_MBP_User.Text.Replace(" ","") -ne "") -and $TB_MBP_User.Text -ne "User Email")
            {
                $MBP_User = Get-OWAMailbox $TB_MBP_User.Text
                $RTB_MBP_Output.AppendText("`nUser: " + $MBP_User.PrimarySmtpAddress)
                . updateMBPOutput

                if($CB_MBP_SendAs.Checked){
                    
                    Add-ADPermission -Identity "$($MBP_Target.PrimarySmtpAddress)" -User "$($MBP_User.PrimarySmtpAddress)" -ExtendedRights "Send As"
                }
                if($CB_MBP_FullAccess.Checked){
                    Add-OWAMailboxPermission -Identity $MBP_Target.PrimarySmtpAddress -User $MBP_User.PrimarySmtpAddress -AccessRights 'FullAccess' | Out-String | ForEach-Object {
                        $RTB_MBP_Output.AppendText("`n" + $_)
                        . updateMBPOutput}

                    add-actionDetails -detailTitle "Mailbox Permission" -detailExplanation "Added FullAccess Mailbox Permission ($($TB_MBP_User.Text))" -actionElement $setMBAction
                }
            }
            if ($CB_MBP_SendSize.Checked)
            {
                Set-OWAMailbox $TB_MBP_Target -MaxSendSize "$($TB_SendSize.Text)MB" | Out-String | ForEach-Object {
                    $RTB_MBP_Output.AppendText("`n" + $_)
                    . updateMBPOutput
                }
                add-actionDetails -detailTitle "Max Send Size Changed" -detailExplanation "Set MaxSendSize $($TB_SendSize.Text)MB" -actionElement $setMBAction
            }
            if ($CB_MBP_ReceiveSize.Checked)
            {
                Set-OWAMailbox $TB_MBP_Target -MaxReceiveSize "$($TB_ReceiveSize.Text)MB" | Out-String | ForEach-Object {
                    $RTB_MBP_Output.AppendText("`n" + $_)
                    . updateMBPOutput
                }
                add-actionDetails -detailTitle "Max Receive Size Changed" -detailExplanation "Set MaxReveiveSize $($TB_ReceiveSize.Text)MB" -actionElement $setMBAction
            }
            if ($HideGal.Checked)
            {
                Set-OWAMailbox "$($TB_MBP_Target.Text)" -HiddenFromAddressListsEnabled $True

                add-actionDetails -detailTitle "Hidden From GAL" -detailExplanation "True" -actionElement $setMBAction
            }
        }
        $TB_MBP_User.Text = ""
        $TB_MBP_Target.Text = ""
        $CB_MBP_SendAs.Checked = $false
        $CB_MBP_FullAccess.Checked = $false
        $RB_M.Checked = $false
        $RB_S.Checked = $false
        $RB_R.Checked = $false
        save-actionElementToSessionLog -element $setMBAction
        save-sessionLog -log $sessionLog -element $sessionElement
    }
    #endregion Set MBPerms

    #region CMS Group
    $handler_CMS_Create_Click= 
    {
        $cms_action = add-ActionElementToSessionLog -action "Creating CMS"
        $CMS_Status.text = ""
        $alias = ($CMS_Group.text).Replace(" ","")
        $owners = ($CMS_Owners.text).Replace(" ","")
        $ownerarray = $owners.split(",")

        $CMS_Progress.Value = 0
        $CMS_Progress.Step = 100/11

        $CMS_Status.text = "Creating Group"
        $CMS_Progress.PerformStep()
        $form1.Update()

        New-LocalDistributionGroup -alias $alias -name $CMS_Group.text -type security -org "OU=CMS,OU=DLs,OU=Exchange,dc=sooner,dc=net,dc=ou,dc=edu" -SamAccountName $alias
        add-actionDetails -detailTitle "Created New Group" -detailExplanation "Alias: $($alias)" -actionElement $cms_action

        $CMS_Status.text = "Setting Email Policy"
        $CMS_Progress.PerformStep()
        $form1.Update()
    
        Set-LocalDistributionGroup $alias -BypassSecurityGroupManagerCheck -EmailAddressPolicyEnabled $false
        add-actionDetails -detailTitle "Setting Email Policy" -detailExplanation "EmailAddressPolicy: False" -actionElement $cms_action

        $CMS_Status.text = "Setting Owners"
        $CMS_Progress.PerformStep()
        $form1.Update()

        foreach ($person in $ownerarray) {
            $DLmangers = (Get-LocalDistributionGroup $alias).ManagedBy
            $DLmangers += $person
            Set-LocalDistributionGroup $alias -ManagedBy $DLmangers
        }
        add-actionDetails -detailTitle "Adding Owners" -detailExplanation "Added Owners" -actionElement $cms_action

        $CMS_Status.text = "Waiting for Replication"
    
        $i = 0
        do {
            $CMS_Progress.PerformStep()
            $form1.Update()
            sleep 1
            $i ++
        } while ($i -lt 5)

        $CMS_Status.text = "Setting Address"
        $CMS_Progress.PerformStep()
        $form1.Update()
    
        Set-LocalDistributionGroup $alias -PrimarySMTPAddress $alias@ou.edu
    
        add-actionDetails -detailTitle "Setting Address" -detailExplanation "Primary SMTP: $($alias)@ou.edu" -actionElement $cms_action

        if($CMS_Members.Text -ne ""){
            $CMS_Status.text = "Adding Members"
            $CMS_Progress.PerformStep()
            $form1.Update()
            $memberList = $CMS_Members.Text.Split("`n")
            add-actionDetails -detailTitle "Adding Members" -detailExplanation "Added Members" -actionElement $cms_action
            $memberList | foreach {Add-LocalDistributionGroupMember -Identity $CMS_Group.Text -Member $_}
            $CMS_Status.text = "Members Added"
            $form1.Update()
        }

        $CMS_Status.text = "Verifying Data"
        $CMS_Progress.PerformStep()
        $form1.Update()
        
        $dlname = (Get-LocalDistributionGroup $alias@ou.edu).name
        $dladdress = (Get-LocalDistributionGroup $alias@ou.edu).PrimarySmtpAddress
    
        if ($dlname -ne "" -and $dladdress -ne "") {
            $CMS_Progress.Value = 100
            $CMS_Status.text = "Done: " + $dlname + " / " + $dladdress
            sleep 2
        }else{
            $CMS_Status.text = "Somethings didn't go right. See console"
        }
    
        $CMS_Group.text = ""
        $CMS_Owners.text = ""
        $CMS_Members.text = ""
        $CMS_Progress.Value = 0
    }
    #endregion Set MBPerms


    #region Unblock Click

    #$handler_Unblock_OnClick =
    #{
    # $LocalUnblockAction = add-ActionElementToSessionLog -action "Local Edge Unblock"
    # $value = Get-ItemProperty -Path "$($key)\SCGUI"
    # $secure = ConvertTo-SecureString -String "$($value.b)" -AsPlainText -Force

    # $fedC = New-Object System.Management.Automation.PSCredential -ArgumentList "it-fedex\BlockUser", $secure
    # $upsC = New-Object System.Management.Automation.PSCredential -ArgumentList "it-ups\BlockUser", $secure

    # New-PSDrive -Name Fedex -PSProvider FileSystem -Root "\\it-fedex\C$" -Credential $fedC | out-string |Out-Host
        
    # New-PSDrive -Name UPS -PSProvider FileSystem -Root "\\it-ups\C$" -Credential $upsC | Out-String | Out-Host
        
    # $users = $RTB_User.Text.Split("`n")
    # $currentUnblockUser = 1
    # [xml] $fedStatus = Get-Content "Fedex:\UserToUnblock\status\status.xml"
    # $FedexUnblockList = "Fedex:\UserToUnblock\users.txt"

    # [xml] $upsStatus = Get-Content "\\it-ups\UserToUnblock\status\status.xml"
    # $UpsUnblockList = "\\it-ups\UserToUnblock\users.txt"
    # foreach ($user in $users)
    # {
    # $dandt = Get-Date -Format g
    # if ($currentUnblockUser -eq $users.count)
    # {
    # $RTB_UnblockConsole.AppendText("[$($dandt)] Unblocking $($user)")
    # }
    # else
    # {
    # $RTB_UnblockConsole.AppendText("[$($dandt)] Unblocking $($user)`n")
    # }
    # if ($fedStatus.Status.unblock.value -eq "True")
    # {
    # Add-content "Fedex:\UserToUnblock\tmp.txt" "$($user)"
    # add-actionDetails -detailTitle "Unblock currently Active (FEDEX)" -detailExplanation "Added ($($user)) to tmp.text while waiting for script to complete." -actionElement $LocalUnblockAction
    # }
    # else
    # {
    # Add-content $FedexUnblockList "$($user)"
    # add-actionDetails -detailTitle "(Fedex) Unblock User" -detailExplanation "User ($($user)) has been added to unblock list" -actionElement $LocalUnblockAction
    # }

            
    # if ($upsStatus.Status.unblock.value -eq "True")
    # {
    # Add-content "\\it-ups\UserToUnblock\tmp.txt" "$($user)"
    # add-actionDetails -detailTitle "Unblock currently Active (UPS)" -detailExplanation "Added ($($user)) to tmp.text while waiting for script to complete." -actionElement $LocalUnblockAction
    # }
    # else
    # {
    # Add-Content $upsUnblockList "$($user)" # (Accessible on laggier)
    # add-actionDetails -detailTitle "(Ups) Unblock User" -detailExplanation "User ($($user)) has been added to unblock list" -actionElement $LocalUnblockAction
    # }
    # $currentUnblockUser++
    # }
    # $RTB_UnblockConsole.AppendText("`n")
    # save-actionElementToSessionLog -element $LocalUnblockAction
    # save-sessionLog -log $sessionLog -element $sessionElement
    # #TODO Fix this method on local exchange servers.
    #}

    #endregion

    function refresh_OWABlockedUsers()
    {    
        $id = Get-Random -Minimum 10000 -Maximum 999999
        $letters = @("A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z")
        $randomLetter = $letters[(Get-Random -Minimum 0 -Maximum 25)]
        $value = "$($randomLetter)$($id)"
        Write-Host $value
        Invoke-Command -Session (Get-PSSession -Name "Office 365") -ScriptBlock {Get-BlockedSenderAddress} -AsJob -JobName $value
        
        do 
        {
            if ((Get-Job -Name "$value").State -eq "Completed")
            {
                $results = Receive-Job -Name "$value"
                $DGV_BlockedUsers.Rows.Clear()

                $form1.Cursor = "WaitCursor"
                $notifyIcon.ShowBalloonTip("20000", "Refreshing Block Users", "Refreshing the OWA Blocked Users List. Please Wait.", "Info")
                foreach ($sender in $results)
                {
                    $userMB = Get-OWAMailbox $sender.SenderAddress
                    $name = $userMB.DisplayName.Split(",")
                    $DGV_BlockedUsers.Rows.Add("$($name[1]) $($name[0])", "$($sender.SenderAddress)")
                }
                $form1.Cursor = "Default"
            }
        } while ((Get-Job -Name "$value").State -eq "Running")
        
    }
    $OnLoadForm_StateCorrection=
    {#Correct the initial state of the form to prevent the .Net maximized form issue
        $form1.WindowState = $InitialFormWindowState
    }

    #----------------------------------------------
    #region Generated Form Code

    $System_Drawing_Size = New-Object System.Drawing.Size
    $System_Drawing_Size.Height = 450
    $System_Drawing_Size.Width = 660
    $form1.ClientSize = $System_Drawing_Size
    $form1.MaximumSize = $System_Drawing_Size
    $form1.MinimumSize = $System_Drawing_Size
    $form1.MaximizeBox = $false
    $form1.DataBindings.DefaultDataSourceUpdateMode = 0
    $form1.Icon = [System.Drawing.Icon]::ExtractAssociatedIcon('C:\Program Files\Common Files\server_earth_aTu_icon.ico')
    $form1.Name = "SCGUI"
    $form1.Text = "SCGUI $($env:ConnectedServerType)"
    $form1.StartPosition = 1

    $menuBar = New-Object System.Windows.Forms.MenuStrip
    $ConnectedStatus = New-Object System.Windows.Forms.ToolStripMenuItem
    $ConnectedStatus.Text = "Connection Status"
    $menuBar.Items.Add($ConnectedStatus)

    $connected = New-Object System.Windows.Forms.ToolStripMenuItem
    $connected.Text = "Connected Servers"
    $localConnection = New-Object System.Windows.Forms.ToolStripMenuItem
    $localConnection.Text = "Local Exchange: Disconnected"
    if($env:isLocalConnected -eq "YES")
    {
        $localConnection.Text = "Local Exchange: Connected"
    }
    $connected.DropDownItems.Add($localConnection)

    $OWAConnection = New-Object System.Windows.Forms.ToolStripMenuItem
    $OWAConnection.Text = "Office 365: Disconnected"
    if ($env:isOWAConnected -eq "YES")
    {
        $OWAConnection.Text = "Office 365: Connected"
    }
    $connected.DropDownItems.Add($OWAConnection)
    $ConnectedStatus.DropDownItems.Add($connected)
    $Connecteduser = New-Object System.Windows.Forms.ToolStripMenuItem
    $Connecteduser.Text = "User: $($env:USERDOMAIN)$($env:USERNAME)"
    $ConnectedStatus.DropDownItems.Add($Connecteduser)

    $logOut = New-Object System.Windows.Forms.ToolStripMenuItem
    $logOut.Text = "Log Out"
    $logOut.Add_Click({
        $form1.Close()
        $loginForm.Visible = $True
        $sessions = Get-PSSession 
        $sessions | Remove-PSSession
    })

    $ConnectedStatus.DropDownItems.Add($logOut)

    $form1.Controls.Add($menuBar)
    
    $tabControl1.DataBindings.DefaultDataSourceUpdateMode = 0
    $System_Drawing_Point = New-Object System.Drawing.Point
    $System_Drawing_Point.X = 0
    $System_Drawing_Point.Y = 25
    $tabControl1.Location = $System_Drawing_Point
    $tabControl1.Name = "tabControl1"
    $tabControl1.SelectedIndex = 0
    $System_Drawing_Size = New-Object System.Drawing.Size
    $System_Drawing_Size.Height = 388
    $System_Drawing_Size.Width = 645
    $tabControl1.Size = $System_Drawing_Size
    $tabControl1.TabIndex = 0

    $form1.Controls.Add($tabControl1)

    
    #region Create DL
    function validateDLInput(){

        if ($TB_EmailAddress.Text.Length -gt 0)
        {
            if (($TB_EmailAddress.Text.Substring(0,1) -match "^[a-zA-Z0-9]") -and ($TB_EmailAddress.Text.Substring(($TB_EmailAddress.Text.Length - 1), 1) -match "^[a-zA-Z0-9]"))
            {
                $TB_EmailAddressValid = $True
            } else {
                [System.Windows.MessageBox]::Show("Email Format is Incorrect.`nFirst and last charcter must be an Alphanumeric Character (a-z)(0-9)", "Incorrect Format", "OK", "Warning")
                $Create.Enabled = $false
                return
            }
        }
        if ($TB_DGN.Text.Length -gt 0) {
            if (($TB_DGN.Text.Substring(0,1) -match "^[a-zA-Z0-9]") -and ($TB_DGN.Text.Substring(($TB_DGN.Text.Length - 1), 1) -match "^[a-zA-Z0-9]"))
            {
                $TB_DGNValid = $True
                if (!$TB_EmailAddressValid)
                {
                    $TB_EmailAddress.Text = $TB_DGN.Text
                }
            } else {
                [System.Windows.MessageBox]::Show("Distribuion Group Name Incorrect.`nFirst and last charcter must be an Alphanumeric Character (a-z)(0-9)", "Incorrect Format", "OK", "Warning")
                $Create.Enabled = $false
                return
            }
        }
        if ($TB_EmailAddressValid -and $TB_DGNValid)
        {
            $Create.Enabled = $True
        }
    }

    $tabPageDL.DataBindings.DefaultDataSourceUpdateMode = 0
    $System_Drawing_Point = New-Object System.Drawing.Point
    $System_Drawing_Point.X = 4
    $System_Drawing_Point.Y = 22
    $tabPageDL.Location = $System_Drawing_Point
    $tabPageDL.Name = "tabPageDL"
    $System_Windows_Forms_Padding = New-Object System.Windows.Forms.Padding
    $System_Windows_Forms_Padding.All = 3
    $System_Windows_Forms_Padding.Bottom = 3
    $System_Windows_Forms_Padding.Left = 3
    $System_Windows_Forms_Padding.Right = 3
    $System_Windows_Forms_Padding.Top = 3
    $tabPageDL.Padding = $System_Windows_Forms_Padding
    $System_Drawing_Size = New-Object System.Drawing.Size
    $System_Drawing_Size.Height = 362
    $System_Drawing_Size.Width = 637
    $tabPageDL.Size = $System_Drawing_Size
    $tabPageDL.TabIndex = 0
    $tabPageDL.Text = "Create DL"
    $tabPageDL.UseVisualStyleBackColor = $True
    if ($env:isLocalConnected -eq "YES")
    {
        $tabControl1.Controls.Add($tabPageDL)
    }

    $groupBox2.DataBindings.DefaultDataSourceUpdateMode = 0
    $System_Drawing_Point = New-Object System.Drawing.Point
    $System_Drawing_Point.X = 428
    $System_Drawing_Point.Y = 7
    $groupBox2.Location = $System_Drawing_Point
    $groupBox2.Name = "groupBox2"
    $System_Drawing_Size = New-Object System.Drawing.Size
    $System_Drawing_Size.Height = 168
    $System_Drawing_Size.Width = 200
    $groupBox2.Size = $System_Drawing_Size
    $groupBox2.TabIndex = 13
    $groupBox2.TabStop = $False
    $groupBox2.Text = "Members"

    $tabPageDL.Controls.Add($groupBox2)

    $CB_Sponsors.Checked = $True
    $CB_Sponsors.CheckState = 1
    $CB_Sponsors.DataBindings.DefaultDataSourceUpdateMode = 0

    $System_Drawing_Point = New-Object System.Drawing.Point
    $System_Drawing_Point.X = 7
    $System_Drawing_Point.Y = 150
    $CB_Sponsors.Location = $System_Drawing_Point
    $CB_Sponsors.Name = "CB_Sponsors"
    $System_Drawing_Size = New-Object System.Drawing.Size
    $System_Drawing_Size.Height = 15
    $System_Drawing_Size.Width = 187
    $CB_Sponsors.Size = $System_Drawing_Size
    $CB_Sponsors.TabIndex = 11
    $CB_Sponsors.Text = "Add Sponsors?"
    $CB_Sponsors.UseVisualStyleBackColor = $True

    $groupBox2.Controls.Add($CB_Sponsors)

    $RTB_Members.DataBindings.DefaultDataSourceUpdateMode = 0
    $RTB_Members.DetectUrls = $False
    $RTB_Members.EnableAutoDragDrop = $True
    $System_Drawing_Point = New-Object System.Drawing.Point
    $System_Drawing_Point.X = 7
    $System_Drawing_Point.Y = 14
    $RTB_Members.Location = $System_Drawing_Point
    $RTB_Members.Name = "RTB_Members"
    $System_Drawing_Size = New-Object System.Drawing.Size
    $System_Drawing_Size.Height = 131
    $System_Drawing_Size.Width = 187
    $RTB_Members.Size = $System_Drawing_Size
    $RTB_Members.TabIndex = 10
    $RTB_Members.Text = ""
    $uploadCsv.Text = "Upload Members (CSV)"
    $uploadCsv.Add_Click({
        $csv = Import-Csv (get-File) -Header @("User")
        foreach ($line in $csv)
        {
            $RTB_Members.AppendText("$($line.User)`n")
        }

    })
    $uploadDLMembers.Items.Add($uploadCsv)
    $RTB_Members.ContextMenuStrip = $uploadDLMembers

    $groupBox2.Controls.Add($RTB_Members)

    $label4.DataBindings.DefaultDataSourceUpdateMode = 0

    $System_Drawing_Point = New-Object System.Drawing.Point
    $System_Drawing_Point.X = 152
    $System_Drawing_Point.Y = 158
    $label4.Location = $System_Drawing_Point
    $label4.Name = "label4"
    $System_Drawing_Size = New-Object System.Drawing.Size
    $System_Drawing_Size.Height = 15
    $System_Drawing_Size.Width = 51
    $label4.Size = $System_Drawing_Size
    #$label4.TabIndex = 12
    $label4.Text = "@ou.edu"
    $label4.add_Click($handler_label4_Click)

    $tabPageDL.Controls.Add($label4)

    $RTB_DLOutput.DataBindings.DefaultDataSourceUpdateMode = 0
    $System_Drawing_Point = New-Object System.Drawing.Point
    $System_Drawing_Point.X = 6
    $System_Drawing_Point.Y = 211
    $RTB_DLOutput.Location = $System_Drawing_Point
    $RTB_DLOutput.Name = "RTB_DLOutput"
    $RTB_DLOutput.ReadOnly = $true
    $System_Drawing_Size = New-Object System.Drawing.Size
    $System_Drawing_Size.Height = 145
    $System_Drawing_Size.Width = 625
    $RTB_DLOutput.Size = $System_Drawing_Size
    #$RTB_DLOutput.TabIndex = 11
    $RTB_DLOutput.Text = ""

    $tabPageDL.Controls.Add($RTB_DLOutput)


    $Create.DataBindings.DefaultDataSourceUpdateMode = 0

    $System_Drawing_Point = New-Object System.Drawing.Point
    $System_Drawing_Point.X = 531
    $System_Drawing_Point.Y = 182
    $Create.Location = $System_Drawing_Point
    $Create.Name = "Create"
    $System_Drawing_Size = New-Object System.Drawing.Size
    $System_Drawing_Size.Height = 23
    $System_Drawing_Size.Width = 91
    $Create.Size = $System_Drawing_Size
    $Create.TabIndex = 12
    $Create.Text = "Create"
    $Create.UseVisualStyleBackColor = $True
    $Create.add_Click($Create_OnClick)
    $Create.Enabled = $false

    $tabPageDL.Controls.Add($Create)


    $ListInGAL.DataBindings.DefaultDataSourceUpdateMode = 0

    $System_Drawing_Point = New-Object System.Drawing.Point
    $System_Drawing_Point.X = 428
    $System_Drawing_Point.Y = 181
    $ListInGAL.Location = $System_Drawing_Point
    $ListInGAL.Name = "ListInGAL"
    $System_Drawing_Size = New-Object System.Drawing.Size
    $System_Drawing_Size.Height = 24
    $System_Drawing_Size.Width = 104
    $ListInGAL.Size = $System_Drawing_Size
    $ListInGAL.TabIndex = 5
    $ListInGAL.Text = "List in GAL?"
    $ListInGAL.Checked = $true
    $ListInGAL.UseVisualStyleBackColor = $True

    $tabPageDL.Controls.Add($ListInGAL)


    $groupBox1.DataBindings.DefaultDataSourceUpdateMode = 0
    $System_Drawing_Point = New-Object System.Drawing.Point
    $System_Drawing_Point.X = 213
    $System_Drawing_Point.Y = 7
    $groupBox1.Location = $System_Drawing_Point
    $groupBox1.Name = "groupBox1"
    $System_Drawing_Size = New-Object System.Drawing.Size
    $System_Drawing_Size.Height = 86
    $System_Drawing_Size.Width = 208
    $groupBox1.Size = $System_Drawing_Size
    $groupBox1.TabIndex = 6
    $groupBox1.TabStop = $False
    $groupBox1.Text = "Who can send to list?"

    $tabPageDL.Controls.Add($groupBox1)

    $RB_IO.DataBindings.DefaultDataSourceUpdateMode = 0

    $System_Drawing_Point = New-Object System.Drawing.Point
    $System_Drawing_Point.X = 116
    $System_Drawing_Point.Y = 50
    $RB_IO.Location = $System_Drawing_Point
    $RB_IO.Name = "RB_IO"
    $System_Drawing_Size = New-Object System.Drawing.Size
    $System_Drawing_Size.Height = 30
    $System_Drawing_Size.Width = 85
    $RB_IO.Size = $System_Drawing_Size
    $RB_IO.TabIndex = 9
    $RB_IO.TabStop = $True
    $RB_IO.Text = "Internal Only"
    $RB_IO.UseVisualStyleBackColor = $True

    $groupBox1.Controls.Add($RB_IO)


    $RB_OO.DataBindings.DefaultDataSourceUpdateMode = 0

    $System_Drawing_Point = New-Object System.Drawing.Point
    $System_Drawing_Point.X = 117
    $System_Drawing_Point.Y = 20
    $RB_OO.Location = $System_Drawing_Point
    $RB_OO.Name = "RB_OO"
    $System_Drawing_Size = New-Object System.Drawing.Size
    $System_Drawing_Size.Height = 30
    $System_Drawing_Size.Width = 85
    $RB_OO.Size = $System_Drawing_Size
    $RB_OO.TabIndex = 8
    $RB_OO.TabStop = $True
    $RB_OO.Text = "Owners Only"
    $RB_OO.UseVisualStyleBackColor = $True

    $groupBox1.Controls.Add($RB_OO)


    $RB_MO.DataBindings.DefaultDataSourceUpdateMode = 0

    $System_Drawing_Point = New-Object System.Drawing.Point
    $System_Drawing_Point.X = 6
    $System_Drawing_Point.Y = 49
    $RB_MO.Location = $System_Drawing_Point
    $RB_MO.Name = "RB_MO"
    $System_Drawing_Size = New-Object System.Drawing.Size
    $System_Drawing_Size.Height = 24
    $System_Drawing_Size.Width = 104
    $RB_MO.Size = $System_Drawing_Size
    $RB_MO.TabIndex = 7
    $RB_MO.TabStop = $True
    $RB_MO.Text = "Members Only"
    $RB_MO.UseVisualStyleBackColor = $True

    $groupBox1.Controls.Add($RB_MO)


    $RB_A.Checked = $True
    $RB_A.DataBindings.DefaultDataSourceUpdateMode = 0

    $System_Drawing_Point = New-Object System.Drawing.Point
    $System_Drawing_Point.X = 6
    $System_Drawing_Point.Y = 19
    $RB_A.Location = $System_Drawing_Point
    $RB_A.Name = "RB_A"
    $System_Drawing_Size = New-Object System.Drawing.Size
    $System_Drawing_Size.Height = 24
    $System_Drawing_Size.Width = 104
    $RB_A.Size = $System_Drawing_Size
    $RB_A.TabIndex = 6
    $RB_A.TabStop = $True
    $RB_A.Text = "Anyone"
    $RB_A.UseVisualStyleBackColor = $True

    $groupBox1.Controls.Add($RB_A)

    $TB_EmailAddress.DataBindings.DefaultDataSourceUpdateMode = 0
    $System_Drawing_Point = New-Object System.Drawing.Point
    $System_Drawing_Point.X = 6
    $System_Drawing_Point.Y = 155
    $TB_EmailAddress.Location = $System_Drawing_Point
    $TB_EmailAddress.Name = "TB_EmailAddress"
    $System_Drawing_Size = New-Object System.Drawing.Size
    $System_Drawing_Size.Height = 20
    $System_Drawing_Size.Width = 145
    $TB_EmailAddress.Size = $System_Drawing_Size
    $TB_EmailAddress.TabIndex = 4

    $TB_EmailAddress.Add_Leave({
        validateDLInput
    })

    $tabPageDL.Controls.Add($TB_EmailAddress)

    $label3.DataBindings.DefaultDataSourceUpdateMode = 0
    $System_Drawing_Point = New-Object System.Drawing.Point
    $System_Drawing_Point.X = 6
    $System_Drawing_Point.Y = 137
    $label3.Location = $System_Drawing_Point
    $label3.Name = "label3"
    $System_Drawing_Size = New-Object System.Drawing.Size
    $System_Drawing_Size.Height = 15
    $System_Drawing_Size.Width = 195
    $label3.Size = $System_Drawing_Size
    #$label3.TabIndex = 6
    $label3.Text = "@ou.edu Address (Optional)"

    $tabPageDL.Controls.Add($label3)

    $TB_Sponsors.DataBindings.DefaultDataSourceUpdateMode = 0
    $System_Drawing_Point = New-Object System.Drawing.Point
    $System_Drawing_Point.X = 6
    $System_Drawing_Point.Y = 114
    $TB_Sponsors.Location = $System_Drawing_Point
    $TB_Sponsors.Name = "TB_Sponsors"
    $System_Drawing_Size = New-Object System.Drawing.Size
    $System_Drawing_Size.Height = 20
    $System_Drawing_Size.Width = 197
    $TB_Sponsors.Size = $System_Drawing_Size
    $TB_Sponsors.TabIndex = 3

    $uploadSponsersCsv.Text = "Upload Sponsers"
    $uploadSponsersCsv.Add_Click({
        $csv = Import-Csv (get-File) -Header "User"
        foreach ($line in $csv)
        {
            $TB_Sponsors.AppendText("$($line.User), ") #TODO Figure out clean method to do this
        }
    })
        $uploadSponsers.Items.Add($uploadSponsersCsv)
    $TB_Sponsors.ContextMenuStrip = $uploadSponsers

    $tabPageDL.Controls.Add($TB_Sponsors)

    $label2.DataBindings.DefaultDataSourceUpdateMode = 0

    $System_Drawing_Point = New-Object System.Drawing.Point
    $System_Drawing_Point.X = 6
    $System_Drawing_Point.Y = 96
    $label2.Location = $System_Drawing_Point
    $label2.Name = "label2"
    $System_Drawing_Size = New-Object System.Drawing.Size
    $System_Drawing_Size.Height = 15
    $System_Drawing_Size.Width = 197
    $label2.Size = $System_Drawing_Size
    #$label2.TabIndex = 4
    $label2.Text = "Comma-Separated List of Sponsors"

    $tabPageDL.Controls.Add($label2)

    $TB_Alias.DataBindings.DefaultDataSourceUpdateMode = 0
    $System_Drawing_Point = New-Object System.Drawing.Point
    $System_Drawing_Point.X = 6
    $System_Drawing_Point.Y = 73
    $TB_Alias.Location = $System_Drawing_Point
    $TB_Alias.Name = "TB_Alias"
    $System_Drawing_Size = New-Object System.Drawing.Size
    $System_Drawing_Size.Height = 20
    $System_Drawing_Size.Width = 197
    $TB_Alias.Size = $System_Drawing_Size
    $TB_Alias.TabIndex = 2

    $tabPageDL.Controls.Add($TB_Alias)


    $UseCustomAlias.DataBindings.DefaultDataSourceUpdateMode = 0

    $System_Drawing_Point = New-Object System.Drawing.Point
    $System_Drawing_Point.X = 6
    $System_Drawing_Point.Y = 52
    $UseCustomAlias.Location = $System_Drawing_Point
    $UseCustomAlias.Name = "UseCustomAlias"
    $System_Drawing_Size = New-Object System.Drawing.Size
    $System_Drawing_Size.Height = 15
    $System_Drawing_Size.Width = 197
    $UseCustomAlias.Size = $System_Drawing_Size
    $UseCustomAlias.TabIndex = 1
    $UseCustomAlias.Text = "Use Custom Alias"
    $UseCustomAlias.UseVisualStyleBackColor = $True

    $tabPageDL.Controls.Add($UseCustomAlias)

    $TB_DGN.DataBindings.DefaultDataSourceUpdateMode = 0
    $System_Drawing_Point = New-Object System.Drawing.Point
    $System_Drawing_Point.X = 6
    $System_Drawing_Point.Y = 21
    $TB_DGN.Location = $System_Drawing_Point
    $TB_DGN.Name = "TB_DGN"
    $System_Drawing_Size = New-Object System.Drawing.Size
    $System_Drawing_Size.Height = 20
    $System_Drawing_Size.Width = 197
    $TB_DGN.Size = $System_Drawing_Size
    $TB_DGN.TabIndex = 0

    $TB_DGN.Add_Leave({
        validateDLInput
    })

    $tabPageDL.Controls.Add($TB_DGN)

    $label1.DataBindings.DefaultDataSourceUpdateMode = 0

    $System_Drawing_Point = New-Object System.Drawing.Point
    $System_Drawing_Point.X = 6
    $System_Drawing_Point.Y = 3
    $label1.Location = $System_Drawing_Point
    $label1.Name = "label1"
    $System_Drawing_Size = New-Object System.Drawing.Size
    $System_Drawing_Size.Height = 15
    $System_Drawing_Size.Width = 200
    $label1.Size = $System_Drawing_Size
    #$label1.TabIndex = 0
    $label1.Text = "Distribution Group Name"

    $tabPageDL.Controls.Add($label1)

    $System_Drawing_Point.X = 213
    $System_Drawing_Point.Y = 93
    $GB_DLType.Location = $System_Drawing_Point
    $System_Drawing_Size.Height = 112
    $System_Drawing_Size.Width = 208
    $GB_DLType.Text = "Type?"

    $tabPageDL.Controls.Add($GB_DLType)

    $System_Drawing_Point.X = 6
    $System_Drawing_Point.Y = 22
    $RB_SecurityGroup.Location = $System_Drawing_Point
    $System_Drawing_Size.Height = 17
    $System_Drawing_Size.Width = 175
    $RB_SecurityGroup.Size = $System_Drawing_Size
    $RB_SecurityGroup.Text = "Mail Enabled Security Group"
    $RB_SecurityGroup.Add_CheckedChanged({
        if ($RB_SecurityGroup.Checked)
        {
            $ListInGAL.Checked = $false
        }
        else
        {
            $ListInGAL.Checked = $True
        }
    })

    $GB_DLType.Controls.Add($RB_SecurityGroup)

    $System_Drawing_Point.X = 6
    $System_Drawing_Point.Y = 45
    $RB_DistributionGroup.Location = $System_Drawing_Point
    $System_Drawing_Size.Height = 17
    $System_Drawing_Size.Width = 165
    $RB_DistributionGroup.Size = $System_Drawing_Size
    $RB_DistributionGroup.Text = "Distribution"
    $RB_DistributionGroup.Checked = $True

    $GB_DLType.Controls.Add($RB_DistributionGroup)
    #endregion Create DL

    #region CMS Group

    $CMS_Tab.DataBindings.DefaultDataSourceUpdateMode = 0
    $System_Drawing_Point = New-Object System.Drawing.Point
    $System_Drawing_Point.X = 4
    $System_Drawing_Point.Y = 22
    $CMS_Tab.Location = $System_Drawing_Point
    $CMS_Tab.Name = "CMS_Tab"
    $System_Windows_Forms_Padding = New-Object System.Windows.Forms.Padding
    $System_Windows_Forms_Padding.All = 3
    $System_Windows_Forms_Padding.Bottom = 3
    $System_Windows_Forms_Padding.Left = 3
    $System_Windows_Forms_Padding.Right = 3
    $System_Windows_Forms_Padding.Top = 3
    $CMS_Tab.Padding = $System_Windows_Forms_Padding
    $System_Drawing_Size = New-Object System.Drawing.Size
    $System_Drawing_Size.Height = 364
    $System_Drawing_Size.Width = 637
    $CMS_Tab.Size = $System_Drawing_Size
    $CMS_Tab.TabIndex = 0
    $CMS_Tab.Text = "CMS Group"
    $CMS_Tab.UseVisualStyleBackColor = $True
    #$CMS_Tab.add_Click($handler_TabPage:_Click)

    if ($env:isLocalConnected -eq "YES")
    {
        $tabControl1.Controls.Add($CMS_Tab)
    }

    $CMS_Status.DataBindings.DefaultDataSourceUpdateMode = 0
    $System_Drawing_Point = New-Object System.Drawing.Point
    $System_Drawing_Point.X = 4
    $System_Drawing_Point.Y = 321
    $CMS_Progress.Location = $System_Drawing_Point
    $CMS_Progress.Name = "CMS_Progress"
    $System_Drawing_Size = New-Object System.Drawing.Size
    $System_Drawing_Size.Height = 23
    $System_Drawing_Size.Width = 200
    $CMS_Progress.Size = $System_Drawing_Size
    #$CMS_Progress.TabIndex = 9
    $CMS_Progress.add_Click($handler_CMS_Progress_Click)

    $CMS_Tab.Controls.Add($CMS_Progress)

    $CMS_Status.DataBindings.DefaultDataSourceUpdateMode = 0

    $System_Drawing_Point = New-Object System.Drawing.Point
    $System_Drawing_Point.X = 4
    $System_Drawing_Point.Y = 303
    $CMS_Status.Location = $System_Drawing_Point
    $CMS_Status.Name = "CMS_Status"
    $System_Drawing_Size = New-Object System.Drawing.Size
    $System_Drawing_Size.Height = 15
    $System_Drawing_Size.Width = 400
    $CMS_Status.Size = $System_Drawing_Size
    #$CMS_Status.TabIndex = 8
    #$CMS_Status.TextAlign = 4

    $CMS_Tab.Controls.Add($CMS_Status)

    $CMS_Members.DataBindings.DefaultDataSourceUpdateMode = 0
    $System_Drawing_Point = New-Object System.Drawing.Point
    $System_Drawing_Point.X = 4
    $System_Drawing_Point.Y = 115
    $CMS_Members.Location = $System_Drawing_Point
    $CMS_Members.Name = "CMS_Members"
    $System_Drawing_Size = New-Object System.Drawing.Size
    $System_Drawing_Size.Height = 156
    $System_Drawing_Size.Width = 197
    $CMS_Members.Size = $System_Drawing_Size
    $CMS_Members.TabIndex = 3
    $CMS_Members.Text = ""

    $uploadCSV_CMS.Text = "Upload CSV" #Add option to upload xml
    $uploadCSV_CMS.Add_Click({
        $csv = Import-Csv (get-File) -Header @("User")
        foreach ($line in $csv)
        {
            $CMS_Members.AppendText("$($line.User)`n")
        }
    })
    $CMS_Context_CMS.Items.Add($uploadCSV_CMS)
    $CMS_Members.ContextMenuStrip = $CMS_Context_CMS



    $CMS_Tab.Controls.Add($CMS_Members)

    $CMS_label3.DataBindings.DefaultDataSourceUpdateMode = 0

    $System_Drawing_Point = New-Object System.Drawing.Point
    $System_Drawing_Point.X = 4
    $System_Drawing_Point.Y = 96
    $CMS_label3.Location = $System_Drawing_Point
    $CMS_label3.Name = "CMS_label3"
    $System_Drawing_Size = New-Object System.Drawing.Size
    $System_Drawing_Size.Height = 15
    $System_Drawing_Size.Width = 200
    $CMS_label3.Size = $System_Drawing_Size
    #$CMS_label3.TabIndex = 6
    $CMS_label3.Text = "Members"

    $CMS_Tab.Controls.Add($CMS_label3)


    $CMS_Create.DataBindings.DefaultDataSourceUpdateMode = 0

    $System_Drawing_Point = New-Object System.Drawing.Point
    $System_Drawing_Point.X = 129
    $System_Drawing_Point.Y = 277
    $CMS_Create.Location = $System_Drawing_Point
    $CMS_Create.Name = "CMS_Create"
    $System_Drawing_Size = New-Object System.Drawing.Size
    $System_Drawing_Size.Height = 23
    $System_Drawing_Size.Width = 75
    $CMS_Create.Size = $System_Drawing_Size
    $CMS_Create.TabIndex = 4
    $CMS_Create.Text = "Create"
    $CMS_Create.UseVisualStyleBackColor = $True
    $CMS_Create.add_Click($handler_CMS_Create_Click)

    $CMS_Tab.Controls.Add($CMS_Create)

    $CMS_Owners.DataBindings.DefaultDataSourceUpdateMode = 0
    $System_Drawing_Point = New-Object System.Drawing.Point
    $System_Drawing_Point.X = 4
    $System_Drawing_Point.Y = 69
    $CMS_Owners.Location = $System_Drawing_Point
    $CMS_Owners.Name = "CMS_Owners"
    $System_Drawing_Size = New-Object System.Drawing.Size
    $System_Drawing_Size.Height = 20
    $System_Drawing_Size.Width = 200
    $CMS_Owners.Size = $System_Drawing_Size
    $CMS_Owners.TabIndex = 2

    $CMS_Tab.Controls.Add($CMS_Owners)

    $CMS_label2.DataBindings.DefaultDataSourceUpdateMode = 0

    $System_Drawing_Point = New-Object System.Drawing.Point
    $System_Drawing_Point.X = 4
    $System_Drawing_Point.Y = 50
    $CMS_label2.Location = $System_Drawing_Point
    $CMS_label2.Name = "CMS_label2"
    $System_Drawing_Size = New-Object System.Drawing.Size
    $System_Drawing_Size.Height = 15
    $System_Drawing_Size.Width = 200
    $CMS_label2.Size = $System_Drawing_Size
    #$CMS_label2.TabIndex = 2
    $CMS_label2.Text = "Owners"

    $CMS_Tab.Controls.Add($CMS_label2)

    $CMS_label1.DataBindings.DefaultDataSourceUpdateMode = 0

    $System_Drawing_Point = New-Object System.Drawing.Point
    $System_Drawing_Point.X = 4
    $System_Drawing_Point.Y = 4
    $CMS_label1.Location = $System_Drawing_Point
    $CMS_label1.Name = "CMS_label1"
    $System_Drawing_Size = New-Object System.Drawing.Size
    $System_Drawing_Size.Height = 15
    $System_Drawing_Size.Width = 200
    $CMS_label1.Size = $System_Drawing_Size
    #$CMS_label1.TabIndex = 1
    $CMS_label1.Text = "CMS Group Name"
    #$CMS_label1.add_Click($handler_label1_Click)

    $CMS_Tab.Controls.Add($CMS_label1)

    $CMS_Group.DataBindings.DefaultDataSourceUpdateMode = 0
    $System_Drawing_Point = New-Object System.Drawing.Point
    $System_Drawing_Point.X = 4
    $System_Drawing_Point.Y = 23
    $CMS_Group.Location = $System_Drawing_Point
    $CMS_Group.Name = "CMS_Group"
    $System_Drawing_Size = New-Object System.Drawing.Size
    $System_Drawing_Size.Height = 20
    $System_Drawing_Size.Width = 200
    $CMS_Group.Size = $System_Drawing_Size
    $CMS_Group.TabIndex = 0
    #$CMS_Group.add_TextChanged($handler_textBox1_TextChanged)

    $CMS_Tab.Controls.Add($CMS_Group)
    #endregion CMS Group

    #region Group Membership LOCAL
    $membershipTab.Text = "Group Membership"
    $System_Drawing_Point.X = 4
    $System_Drawing_Point.Y = 22
    $membershipTab.Location =$System_Drawing_Point
    $System_Drawing_Size.Height = 364
    $System_Drawing_Size.Width = 637
    $membershipTab.Size = $System_Drawing_Size
    if ($env:isLocalConnected -eq "YES")
    {
        $tabControl1.Controls.Add($membershipTab)
    }

    $GB_DL_SG.Text = "Distribution Group / Security Group"
    $System_Drawing_Point.X = 3
    $System_Drawing_Point.Y = 3
    $GB_DL_SG.Location = $System_Drawing_Point
    $System_Drawing_Size.Height = 52
    $System_Drawing_Size.Width = 256
    $GB_DL_SG.Size = $System_Drawing_Size

    $membershipTab.Controls.Add($GB_DL_SG)

    $GB_Members.Text  = "Members"
    $System_Drawing_Point.X = 3
    $System_Drawing_Point.Y = 61
    $GB_Members.Location = $System_Drawing_Point
    $System_Drawing_Size.Height = 143
    $System_Drawing_Size.Width = 256
    $GB_Members.Size = $System_Drawing_Size

    $membershipTab.Controls.Add($GB_Members)

    $GB_Methods.Text = "Methods"
    $System_Drawing_Point.X = 476
    $System_Drawing_Point.Y = 3
    $GB_Methods.Location = $System_Drawing_Point
    $System_Drawing_Size.Height = 70
    $System_Drawing_Size.Width = 152
    $GB_Methods.Size = $System_Drawing_Size
    $GB_Methods.Visible = $falser

    $membershipTab.Controls.Add($GB_Methods)

    $GB_SetGetMethods.Text = "Get / Set Members"
    $System_Drawing_Point.X = 265
    $System_Drawing_Point.Y = 3
    $GB_SetGetMethods.Location = $System_Drawing_Point
    $System_Drawing_Size.Height = 52
    $System_Drawing_Size.Width = 200
    $GB_SetGetMethods.Size = $System_Drawing_Size

    $membershipTab.Controls.Add($GB_SetGetMethods)

    $GB_ExportOptions.Text = "Export Options"
    $System_Drawing_Point.X = 265
    $System_Drawing_Point.Y = 61
    $GB_ExportOptions.Location = $System_Drawing_Point
    $System_Drawing_Size.Height = 143
    $System_Drawing_Size.Width = 200
    $GB_ExportOptions.Size = $System_Drawing_Size

    $membershipTab.Controls.Add($GB_ExportOptions)
        
    $GB_CurrentMembers.Text = "Current Members"
    $System_Drawing_Point.X = 3
    $System_Drawing_Point.Y = 210
    $GB_CurrentMembers.Location = $System_Drawing_Point
    $System_Drawing_Size.Height = 129
    $System_Drawing_Size.Width = 462
    $GB_CurrentMembers.Size = $System_Drawing_Size

    $membershipTab.Controls.Add($GB_CurrentMembers)

    $GB_MembershipErrors.Text = "Errors"
    $System_Drawing_Point.X = 476
    $System_Drawing_Point.Y = 81
    $GB_MembershipErrors.Location = $System_Drawing_Point
    $System_Drawing_Size.Height = 229
    $System_Drawing_Size.Width = 152
    $GB_MembershipErrors.Size = $System_Drawing_Size

    $membershipTab.Controls.Add($GB_MembershipErrors)

    $System_Drawing_Point.X = 6
    $System_Drawing_Point.Y = 19
    $TB_DLSG_Name.Location = $System_Drawing_Point
    $System_Drawing_Size.Height = 20
    $System_Drawing_Size.Width = 241
    $TB_DLSG_Name.Size = $System_Drawing_Size

    $TB_DLSG_Name.add_Leave({
        if ($TB_DLSG_Name.Text.Length -gt 0)
        {
            if ($DGV_CurrentMembers.RowCount -gt 0)
            {
                $DGV_CurrentMembers.Rows.Clear()
            }
            $members = Get-LocalDistributionGroupMember -identity "$($TB_DLSG_Name.Text)"  -ErrorAction SilentlyContinue
            if ($members)
            {
                if ($members.Count -gt 100)
                {
                    Write-Host "More than 100 Members"
                    for ($i = 0; $i -lt 100; $i++)
                    {
                        $name = "$($members[$i].DisplayName)"
                        $nameArray = $name.Split(",")

                        $DGV_CurrentMembers.Rows.Add("$($nameArray[1]) $($nameArray[0])", "$($members[$i].PrimarySmtpAddress)")
                    }
                } else {
                    foreach ($member in $members)
                    {
                        $name = $($member.DisplayName).split(",")

                        #$DGV_CurrentMembers.Rows.Add("Name", "Email", "4x4")
                        $DGV_CurrentMembers.Rows.Add("$($name[1]) $($name[0])", "$($member.PrimarySmtpAddress)")
                    }
                }
            } else {
                $members = Get-ADGroupMember -identity "$($TB_DLSG_Name.Text)" -ErrorAction SilentlyContinue
                if ($members)
                {
                    foreach ($member in $members)
                    {
                        $user = Get-ADUser "$($member.SamAccountName)" -Properties *

                        $DGV_CurrentMembers.Rows.Add("$($user.GivenName) $($user.SurName)","$($user.UserPrincipalName)")
                    }
                }
            }
        }
    })

    $GB_DL_SG.Controls.Add($TB_DLSG_Name)

    $uploadMembers.Text = "Upload Members (CSV)"
    $uploadMembers.Add_Click({
        $csv = Import-Csv (get-File) -Header "User"
        $count = $csv.count
        $currentObject = 1

        foreach ($line in $csv)
        {
            if ($currentObject -eq $count)
            {
                $RTB_GroupMembership.AppendText("$($line.User)")
            }
            else
            {
                $RTB_GroupMembership.AppendText("$($line.User)`n")
            }
            $currentObject++
        }
    })

    $uploadMembersMenu.Items.Add($uploadMembers)

    $System_Drawing_Point.X = 6
    $System_Drawing_Point.Y = 19
    $RTB_GroupMembership.Location = $System_Drawing_Point
    $System_Drawing_Size.Height = 113
    $System_Drawing_Size.Width = 240
    $RTB_GroupMembership.Size = $System_Drawing_Size

    $RTB_GroupMembership.ContextMenuStrip = $uploadMembersMenu

    $GB_Members.Controls.Add($RTB_GroupMembership)

    $System_Drawing_Point.X = 6
    $System_Drawing_Point.Y = 19
    $DGV_CurrentMembers.Location = $System_Drawing_Point
    $System_Drawing_Size.Height = 96
    $System_Drawing_Size.Width = 448
    $DGV_CurrentMembers.Size = $System_Drawing_Size
    $DGV_CurrentMembers.ReadOnly = $True
    $DGV_CurrentMembers.ColumnCount = 2
    $DGV_CurrentMembers.ColumnHeadersVisible = $True
    $DGV_CurrentMembers.Columns[0].Name = "Name"
    $DGV_CurrentMembers.Columns[1].Name = "User Principal name"
    #$DGV_CurrentMembers.Columns[2].Name = "4x4" #Warning Add back in to use 4x4 in table
    $DGV_CurrentMembers.AutoSizeColumnsMode = "Fill"
    $DGV_CurrentMembers.RowHeadersVisible = $false

    $GB_CurrentMembers.Controls.Add($DGV_CurrentMembers)

    $RB_AddMethod.Text = "Add"
    $System_Drawing_Point.X = 7
    $System_Drawing_Point.Y = 22
    $RB_AddMethod.Location = $System_Drawing_Point
    $System_Drawing_Size.Height = 17
    $System_Drawing_Size.Width = 44
    $RB_AddMethod.Size = $System_Drawing_Size

    $GB_Methods.Controls.Add($RB_AddMethod)

    $RB_RemoveMethod.Text = "Remove"
    $System_Drawing_Point.X = 7
    $System_Drawing_Point.Y = 44
    $RB_RemoveMethod.Location = $System_Drawing_Point
    $System_Drawing_Size.Height = 17
    $System_Drawing_Size.Width = 65
    $RB_RemoveMethod.Size = $System_Drawing_Size

    $GB_Methods.Controls.Add($RB_RemoveMethod)

    $RB_ReplaceMethod.Text = "Replace"
    $System_Drawing_Point.X = 81
    $System_Drawing_Point.Y = 22
    $RB_ReplaceMethod.Location = $System_Drawing_Point
    $System_Drawing_Size.Height = 17
    $System_Drawing_Size.Width = 65
    $RB_ReplaceMethod.Size = $System_Drawing_Size

    $GB_Methods.Controls.Add($RB_ReplaceMethod)

    $RB_GetMethod.Text = "Get Members"
    $System_Drawing_Point.X = 7
    $System_Drawing_Point.Y = 21
    $RB_GetMethod.Location = $System_Drawing_Point
    $System_Drawing_Size.Height = 17
    $System_Drawing_Size.Width = 88
    $RB_GetMethod.Size = $System_Drawing_Size
    $RB_GetMethod.Checked = $True

    $RB_GetMethod.add_CheckedChanged({
        if ($RB_GetMethod.Checked)
        {
            $BN_SetRetrieveMembership.Text = "Export Members"
            $CB_CSVOption.Enabled = $True
            $CB_XML.Enabled = $True
        }
        else
        {
            $CB_CSVOption.Enabled = $false
            $CB_XML.Enabled = $false
        }
    })

    $GB_SetGetMethods.Controls.Add($RB_GetMethod)

    $RB_SetMethod.Text = "Set Members"
    $System_Drawing_Point.X = 105
    $System_Drawing_Point.Y = 21
    $RB_SetMethod.Location = $System_Drawing_Point
    $System_Drawing_Size.Height = 17
    $System_Drawing_Size.Width = 88
    $RB_SetMethod.Size = $System_Drawing_Size

    $RB_SetMethod.Add_CheckedChanged({
        if ($RB_SetMethod.Checked)
        {
            $GB_Methods.Visible = $True
            $BN_SetRetrieveMembership.Text = "Set Members"
            $CB_CSVOption.Enabled = $false
            $CB_XML.Enabled = $false
        }
        else
        {
            $GB_Methods.Visible = $false
            $CB_CSVOption.Enabled = $True
            $CB_XML.Enabled = $True
        }
    })

    $GB_SetGetMethods.Controls.Add($RB_SetMethod)

    $CB_CSVOption.Text = "CSV"
    $System_Drawing_Point.X = 7
    $System_Drawing_Point.Y = 20
    $CB_CSVOption.Location = $System_Drawing_Point
    $System_Drawing_Size.Height = 17
    $System_Drawing_Size.Width = 47
    $CB_CSVOption.Size = $System_Drawing_Size

    $GB_ExportOptions.Controls.Add($CB_CSVOption)

    $CB_XML.Text = "XML"
    $System_Drawing_Point.X = 7
    $System_Drawing_Point.Y = 41
    $CB_XML.Location = $System_Drawing_Point
    $System_Drawing_Size.Height = 17
    $System_Drawing_Size.Width = 80
    $CB_XML.Size = $System_Drawing_Size

    $GB_ExportOptions.Controls.Add($CB_XML)

    $System_Drawing_Point.X = 6
    $System_Drawing_Point.Y = 19
    $RTB_MembershipErrors.Location = $System_Drawing_Point
    $System_Drawing_Size.Height = 204
    $System_Drawing_Size.Width = 140
    $RTB_MembershipErrors.Size = $System_Drawing_Size
    $RTB_MembershipErrors.ScrollBars = "Vertical"
    $RTB_MembershipErrors.ReadOnly = $True

    $GB_MembershipErrors.Controls.Add($RTB_MembershipErrors)

    $BN_SetRetrieveMembership.Text = "Export Members"
    $System_Drawing_Point.X = 528
    $System_Drawing_Point.Y = 316
    $BN_SetRetrieveMembership.Location = $System_Drawing_Point
    $System_Drawing_Size.Height = 23
    $System_Drawing_Size.Width = 100
    $BN_SetRetrieveMembership.Size = $System_Drawing_Size

    $BN_SetRetrieveMembership.Add_Click({
        if ($RB_GetMethod.Checked)
        {
            $exportAction = add-ActionElementToSessionLog -action "Export Group Membership"

            [System.Windows.MessageBox]::Show("Starting Export.", "Export Status", "Ok", "Info")
            if ($CB_CSVOption.Checked -or $CB_XML.Checked)
            {
                if ($CB_CSVOption.Checked)
                {
                    $group = Get-LocalDistributionGroupMember "$($TB_DLSG_Name.Text)" -ErrorAction SilentlyContinue
                    if ($group)
                    {
                        $group | select DisplayName, PrimarySmtpAddress, SamAccountName | ConvertTo-Csv -NoTypeInformation -Delimiter ","[0] | Out-File "$($exportDirectory)\CSV\$($TB_DLSG_Name.Text)-Members.csv"
                    }
                    else
                    {
                        $groupMembers = Get-ADGroupMember -Identity "$($TB_DLSG_Name.Text)"
                        $adUsers = $groupMembers | foreach {Get-ADUser $_ -Properties *}
                         $adUsers | select Surname, GivenName, UserPrincipalName | ConvertTo-Csv -NoTypeInformation -Delimiter ","[0] | Out-File "$($exportDirectory)\CSV\$($TB_DLSG_Name.Text)-Members.csv"
                        
                    }
                    add-actionDetails -detailTitle "Exporting Group Membership CSV" -detailExplanation "Getting all group members of: $($TB_DLSG_Name.Text) into the form of a csv" -actionElement $exportAction
                }
                if ($CB_XML.Checked)
                {
                    [System.XML.XMLDocument] $exportDocument = New-Object System.XML.XMLDocument
                    [System.XML.XMLElement] $membersElement = $exportDocument.CreateElement("Members")
                    $membersElement.SetAttribute("Group", "$($TB_DLSG_Name.Text)")
                    $exportDocument.AppendChild($membersElement)

                    $members = Get-LocalDistributionGroupMember "$($TB_DLSG_Name.Text)" -ErrorAction SilentlyContinue
                    if ($members)
                    {
                        foreach ($member in $members)
                        {
                            [System.XML.XMLElement] $memberElement = $exportDocument.CreateElement("Member")
                            $memberElement.SetAttribute("Name", "$($member.DisplayName)")
                            $memberElement.SetAttribute("UPN", "$($member.PrimarySmtpAddress)")
                            $memberElement.SetAttribute("FourbyFour", "$($member.SamAccountName)")
                            $membersElement.AppendChild($memberElement)
                        }
                    }
                    else
                    {
                        $members = Get-ADGroupMember "$($TB_DLSG_Name.Text)"
                        foreach ($member in $members)
                        {
                            $user = Get-ADUser "$($member.SamAccountName)" -Properties *
                            [System.XML.XMLElement] $memberElement = $exportDocument.CreateElement("Member")
                            $memberElement.SetAttribute("Name", "$($user.GivenName) $($user.Surname)")
                            $memberElement.SetAttribute("UPN", "$($user.UserPrincipalName)")
                            $memberElement.SetAttribute("FourByFour", "$($user.SamAccountName)")
                            $membersElement.AppendChild($memberElement)
                        }
                    }
                    $exportDocument.Save("$($exportDirectory)\XML\$($TB_DLSG_Name.Text)-Members.xml")
                    add-actionDetails -detailTitle "Exporting Group Membership XML" -detailExplanation "Getting all group members of: $($TB_DLSG_Name.Text) into the form of an XML" -actionElement $exportAction
                }
                [System.Windows.MessageBox]::Show("Export has successfully finished", "Info", "Ok", "Info") 
                save-actionElementToSessionLog -element $exportAction
                save-sessionLog -log $sessionLog -element $sessionElement
            }
            $TB_DLSG_Name.Text = ""
            $RB_GetMethod.Checked = $false
            $RB_SetMethod.Checked = $false
            $RTB_GroupMembership.Text = ""
            $CB_CSVOption.Checked = $false
            $CB_XML.Checked = $false
            $DGV_CurrentMembers.Rows.Clear()
        }
            
        if ($RB_SetMethod.Checked)
        {
            $setAction = add-ActionElementToSessionLog -action "Set Distribution / Security Group Membership"
            $members = ($RTB_GroupMembership.Text).Split("`n")
            if (($TB_DLSG_Name.Text -eq "$($env:AdminGroup)") -or ($TB_DLSG_Name.Text -eq "$($env:AdminGroup)@ou.edu"))
            {
                [System.Windows.MessageBox]::Show("Cannot add Members to the specified group.", "Error", "OK", "Info")

                add-actionDetails -detailTitle "Unauthorized Access" -detailExplanation "The user is not allowed to add to $($env:AdminGroup) ad group. Designed in Program" -errorcode "403" -actionElement $setAction
                save-actionElementToSessionLog -element $setAction
                save-sessionLog -log $sessionLog -element $sessionElement
                return
            }
            if ($RB_AddMethod.Checked)
            {
                add-actionDetails -detailTitle "Trying to Add Users" -detailExplanation "$($members)" -actionElement $setAction
                #TODO implement adding group Members
                foreach ($member in $members)
                {
                    try {
                        Add-LocalDistributionGroupMember "$($TB_DLSG_Name.Text)" -Member $member -BypassSecurityGroupManagerCheck 
                        add-actionDetails -detailTitle "Adding Group Members" -detailExplanation "$($env:USERNAME) added $($member)" -actionElement $setAction 
                    } catch [System.Exception]
                    {
                        $RTB_MembershipErrors.AppendText("`n" + $_)

                        add-actionDetails -detailTitle "ErrorAdding Group Members" -detailExplanation "An Error Occured when trying to add the group Members" -actionElement $setAction
                    }
                }
            }

            if ($RB_ReplaceMethod.Checked)
            {
                
                $string = ""
                for ($i = 0; $i -lt $members.Count; $i++)
                {
                    if ($i -eq ($members.Count - 1))
                    {
                        $string += "`"$($members[$i])`""
                    }
                    else 
                    {
                        $string += "`"$($members[$i])`","
                    }
                }
                Write-Host $string
                
                try {
                    Update-LocalDistributionGroupMember "$($TB_DLSG_Name.Text)" -Members $members -BypassSecurityGroupManagerCheck -Confirm:$false
                    add-actionDetails -detailTitle "Replacing Group Members" -detailExplanation "New Member: ($string)" -actionElement $setAction
                } catch {
                    $RTB_MembershipErrors.AppendText("`n" + $_)

                    add-actionDetails -detailTitle "Error Adding Group Members" -detailExplanation "Unable to add ($string) to group." -errorcode "401" -actionElement $setAction
                }
            }

            if ($RB_RemoveMethod.Checked)
            {
                add-actionDetails -detailTitle "Removing Group Members" -detailExplanation "Removing Distribution Group Members" -actionElement $setAction
                foreach ($member in $members)
                {
                    try {
                        Remove-LocalDistributionGroupMember "$($TB_DLSG_Name.Text)" -Member $member -BypassSecurityGroupManagerCheck -Confirm:$false
                        add-actionDetails -detailTitle "Removing User from Group" -detailExplanation "User being removed: ($member)" -actionElement $setAction
                    } catch {

                        $RTB_MembershipErrors.AppendText("`n" + $_)

                        add-actionDetails -detailTitle "Error Removing User" -detailExplanation "There was an error that occured when trying to remove: ($member)" -actionElement $setAction
                    }
                }
            }
            save-actionElementToSessionLog -element $setAction
            save-sessionLog -log $sessionLog -element $sessionElement
            [System.Windows.MessageBox]::Show("Action Completed", "Set Members Completion", "Ok", "Info")
            #Clear Form
            $TB_DLSG_Name.Text = ""
            $RB_GetMethod.Checked = $false
            $RB_SetMethod.Checked = $false
            $RTB_GroupMembership.Text = ""
            $CB_CSVOption.Checked = $false
            $CB_XML.Checked = $false
            $DGV_CurrentMembers.Rows.Clear()
        }
    })

    $membershipTab.Controls.Add($BN_SetRetrieveMembership)

    #endregion
        
    #region Set MBPerms OWA Only

    $tabPageMBP.DataBindings.DefaultDataSourceUpdateMode = 0
    $System_Drawing_Point = New-Object System.Drawing.Point
    $System_Drawing_Point.X = 4
    $System_Drawing_Point.Y = 22
    $tabPageMBP.Location = $System_Drawing_Point
    $tabPageMBP.Name = "tabPageMBP"
    $System_Windows_Forms_Padding = New-Object System.Windows.Forms.Padding
    $System_Windows_Forms_Padding.All = 3
    $System_Windows_Forms_Padding.Bottom = 3
    $System_Windows_Forms_Padding.Left = 3
    $System_Windows_Forms_Padding.Right = 3
    $System_Windows_Forms_Padding.Top = 3
    $tabPageMBP.Padding = $System_Windows_Forms_Padding
    $System_Drawing_Size = New-Object System.Drawing.Size
    $System_Drawing_Size.Height = 364
    $System_Drawing_Size.Width = 637
    $tabPageMBP.Size = $System_Drawing_Size
    $tabPageMBP.TabIndex = 0
    $tabPageMBP.Text = "Mailbox Permissions"
    $tabPageMBP.UseVisualStyleBackColor = $True
    if($env:isOWAConnected -eq "YES")
    {
        $tabControl1.Controls.Add($tabPageMBP)
    }
        
    $System_Drawing_Point.X = 11
    $System_Drawing_Point.Y = 7
    $TargetEmail_GB.Location = $System_Drawing_Point
    $System_Drawing_Size.Height = 42
    $System_Drawing_Size.Width = 238
    $TargetEmail_GB.Size = $System_Drawing_Size
    $TargetEmail_GB.Text = "Target Mailbox / Resource"
    $tabPageMBP.Controls.Add($TargetEmail_GB)

    $System_Drawing_Point.X = 21
    $System_Drawing_Point.Y = 16
    $TB_MBP_Target.Location = $System_Drawing_Point
    $System_Drawing_Size.Height = 20
    $System_Drawing_Size.Width = 211
    $TB_MBP_Target.Size = $System_Drawing_Size

    $TB_MBP_Target.Add_Leave({
        if ($TB_MBP_Target.Text -like "*@ou.edu")
        {
            try{
                $mailbox = Get-OWAMailbox $($TB_MBP_Target.Text) -ErrorAction "SilentlyContinue"
                $TB_SendSize.Text = (($mailbox.MaxSendSize).split(" "))[0]
                $TB_ReceiveSize.Text = (($mailbox.MaxReceiveSize).split(" "))[0]
            } catch
            {
                [System.Windows.MessageBox]::Show("Error: `n Mailbox not found for $($TB_MBP_Target.Text)", "Error: 404", "Ok", "Error")
            }
        }
        if ($TB_MBP_Target.Text.Length -eq 0)
        {
            $TB_SendSize.Text = ""
            $TB_ReceiveSize.Text = ""
        }
    })

    $TargetEmail_GB.Controls.Add($TB_MBP_Target)

    $System_Drawing_Point.X = 11
    $System_Drawing_Point.Y = 52
    $properties_GB.Location = $System_Drawing_Point
    $System_Drawing_Size.Height = 116
    $System_Drawing_Size.Width = 238
    $properties_GB.Size = $System_Drawing_Size
    $properties_GB.Text = "Properties"

    $tabPageMBP.Controls.Add($properties_GB)

    $System_Drawing_Point.X = 21
    $System_Drawing_Point.Y = 19
    $CB_MBP_SendAs.Location = $System_Drawing_Point
    $System_Drawing_Size.Width = 104
    $System_Drawing_Size.Height = 15
    $CB_MBP_SendAs.Size = $System_Drawing_Size
    $CB_MBP_SendAs.Text = "Send As"

    $properties_GB.Controls.Add($CB_MBP_SendAs)

    $System_Drawing_Point.X = 21
    $System_Drawing_Point.Y = 40
    $CB_MBP_FullAccess.Location = $System_Drawing_Point
    $System_Drawing_Size.Height = 15
    $System_Drawing_Size.Width = 104
    $CB_MBP_FullAccess.Size = $System_Drawing_Size
    $CB_MBP_FullAccess.Text = "Full Access"

    $properties_GB.Controls.Add($CB_MBP_FullAccess)

    $System_Drawing_Point.X = 21
    $System_Drawing_Point.Y = 61
    $TB_MBP_User.Location = $System_Drawing_Point
    $System_Drawing_Size.Height = 20
    $System_Drawing_Size.Width = 200
    $TB_MBP_User.Size = $System_Drawing_Size
    $TB_MBP_User.Text = "User Email"

    $TB_MBP_User.Add_Click({
        $TB_MBP_User.Text = "";
    })
    $TB_MBP_User.Add_Leave({
        if ($TB_MBP_User.Text.Length -le 0)
        {
            $TB_MBP_User.Text = "User Email"
        }
    })
    $properties_GB.Controls.Add($TB_MBP_User)

    $System_Drawing_Point.X = 256
    $System_Drawing_Point.Y = 7
    $otherSettings_GB.Location = $System_Drawing_Point
    $System_Drawing_Size.Height = 158
    $System_Drawing_Size.Width = 262
    $otherSettings_GB.Size = $System_Drawing_Size
    $otherSettings_GB.Text = "Other Settings"

    $tabPageMBP.Controls.Add($otherSettings_GB)

    $System_Drawing_Point.X = 7
    $System_Drawing_Point.Y = 20
    $CB_MBP_SendSize.Location = $System_Drawing_Point
    $System_Drawing_Size.Height = 17
    $System_Drawing_Size.Width = 80
    $CB_MBP_SendSize.Size = $System_Drawing_Size
    $CB_MBP_SendSize.Text = "Send Size"
        
    $CB_MBP_SendSize.Add_CheckedChanged({
        if ($CB_MBP_SendSize.Checked)
        {
            $TB_SendSize.Enabled = $true
        }
        else
        {
            $TB_SendSize.Enabled = $false
        }
    })
    $otherSettings_GB.Controls.Add($CB_MBP_SendSize)

    $System_Drawing_Point.X = 109
    $System_Drawing_Point.Y = 20
    $TB_SendSize.Location = $System_Drawing_Point
    $System_Drawing_Size.Height = 20
    $System_Drawing_Size.Width = 117
    $TB_SendSize.Size = $System_Drawing_Size
    $TB_SendSize.Enabled = $false
    $TB_SendSize.Add_Click({
        if ($TB_SendSize.Text.Length -gt 0)
        {
            $TB_SendSize.Text = ""
        }
    })
    $TB_SendSize.Add_Leave({
        if ($TB_SendSize.Text.Length -le 0 -and ($TB_MBP_Target.Text -like "*@ou.edu"))
        {
            try{
                $currentSendSize = Get-Mailbox $($TB_MBP_Target.Text) -ErrorAction "SilentlyContinue"
                $TB_SendSize.Text = (($currentSendSize.MaxSendSize).split(" "))[0]
            } catch
            {
                [System.Windows.MessageBox]::Show("Error: `n Mailbox not found for $($TB_MBP_Target.Text)", "Error: 404", "Ok", "Error")
            }
        }
    })

    $otherSettings_GB.Controls.Add($TB_SendSize)

    $System_Drawing_Point.X = 232
    $System_Drawing_Point.Y = 23
    $LB_SendSizeType.Location = $System_Drawing_Point
    $System_Drawing_Size.Height = 15
    $System_Drawing_Size.Width = 23
    $LB_SendSizeType.Size = $System_Drawing_Size
    $LB_SendSizeType.Text = "MB"
    $LB_SendSizeType.BringToFront()
        
    $otherSettings_GB.Controls.Add($LB_SendSizeType)

    $System_Drawing_Point.X = 7
    $System_Drawing_Point.Y = 44
    $CB_MBP_ReceiveSize.Location = $System_Drawing_Point
    $System_Drawing_Size.Height = 17
    $System_Drawing_Size.Width = 89
    $CB_MBP_ReceiveSize.Size = $System_Drawing_Size
    $CB_MBP_ReceiveSize.Text = "Receive Size"
    $CB_MBP_ReceiveSize.Add_CheckedChanged({
        if ($CB_MBP_ReceiveSize.Checked)
        {
            $TB_ReceiveSize.Enabled = $True
        }
        else
        {
            $TB_ReceiveSize.Enabled = $false
        }
    })

    $otherSettings_GB.Controls.Add($CB_MBP_ReceiveSize)

    $System_Drawing_Point.X = 109
    $System_Drawing_Point.Y = 42
    $TB_ReceiveSize.Location = $System_Drawing_Point
    $System_Drawing_Size.Height = 20
    $System_Drawing_Size.Width = 117
    $TB_ReceiveSize.Size = $System_Drawing_Size
    $TB_ReceiveSize.Enabled = $false

    $TB_ReceiveSize.Add_Click({
        if ($TB_ReceiveSize.Text.Length -gt 0)
        {
            $TB_ReceiveSize.Text = ""
        }
    })
    $TB_ReceiveSize.Add_Leave({
        if ($TB_ReceiveSize.Text.Length -le 0 -and ($TB_MBP_Target.Text -like "*@ou.edu"))
        {
            try{
                $currentSendSize = Get-Mailbox $($TB_MBP_Target.Text) -ErrorAction "SilentlyContinue"
                $TB_ReceiveSize.Text = (($currentSendSize.MaxReceiveSize).split(" "))[0]
            } catch
            {
                [System.Windows.MessageBox]::Show("Error: `n Mailbox not found for $($TB_MBP_Target.Text)", "Error: 404", "Ok", "Error")
            }
        }
    })

    $otherSettings_GB.Controls.Add($TB_ReceiveSize)

    $LB_ReceiveSizeType.Text = "MB"
    $System_Drawing_Point.X = 232
    $System_Drawing_Point.Y = 46
    $LB_ReceiveSizeType.Location = $System_Drawing_Point
    $System_Drawing_Size.Height = 15
    $System_Drawing_Size.Width = 23
    $LB_ReceiveSizeType.Size = $System_Drawing_Size
    #$LB_ReceiveSizeType.BringToFront()

    $otherSettings_GB.Controls.Add($LB_ReceiveSizeType)
    #TO Enable adding and changing email forwards we must set DeliverToMailboxAndForward to true

    $HideGal.Text = "Hide from GAL?"
    $System_Drawing_Point.X = 152
    $System_Drawing_Point.Y = 135
    $HideGal.Location = $System_Drawing_Point
    $System_Drawing_Size.Height = 17
    $System_Drawing_Size.Width = 104
    $HideGal.Size = $System_Drawing_Size

    $otherSettings_GB.Controls.Add($HideGal)

    $cGroupBox.Text = "Convert To:"
    $System_Drawing_Point.X = 524
    $System_Drawing_Point.Y = 7
    $cGroupBox.Location = $System_Drawing_Point
    $System_Drawing_Size.Height = 82
    $System_Drawing_Size.Width = 104
    $cGroupBox.Size = $System_Drawing_Size

    $tabPageMBP.Controls.Add($cGroupBox)

    $System_Drawing_Point.X = 6
    $System_Drawing_Point.Y = 20
    $RB_S.Location = $System_Drawing_Point
    $System_Drawing_Size.Height = 15
    $System_Drawing_Size.Width = 100
    $RB_S.Size = $System_Drawing_Size
    $RB_S.Text = "Shared"

    $cGroupBox.Controls.Add($RB_S)

    $RB_R.Text = "Room"
    $System_Drawing_Point.X = 6
    $System_Drawing_Point.Y = 41
    $RB_R.Location = $System_Drawing_Point
    $RB_R.Size = $System_Drawing_Size

    $cGroupBox.Controls.Add($RB_R)
    
    $B_MBP_Set.Text = "Set"
    $System_Drawing_Point.X = 553
    $System_Drawing_Point.Y = 142
    $B_MBP_Set.Location = $System_Drawing_Point
    $System_Drawing_Size.Height = 23
    $System_Drawing_Size.Width = 75
    $B_MBP_Set.Size = $System_Drawing_Size

    $B_MBP_Set.Add_Click($B_MBP_Set_OnClick)

    $tabPageMBP.Controls.Add($B_MBP_Set)

    $System_Drawing_Point.X = 9
    $System_Drawing_Point.Y = 171
    $RTB_MBP_Output.Location = $System_Drawing_Point
    $System_Drawing_Size.Height = 182
    $System_Drawing_Size.Width = 619
    $RTB_MBP_Output.Size = $System_Drawing_Size
    $RTB_MBP_Output.ReadOnly = $True

    $tabPageMBP.Controls.Add($RTB_MBP_Output)



    #endregion SetMBPerms

    #region Console Page
    $tabPageConsole.DataBindings.DefaultDataSourceUpdateMode = 0
    $System_Drawing_Point = New-Object System.Drawing.Point
    $System_Drawing_Point.X = 4
    $System_Drawing_Point.Y = 22
    $tabPageConsole.Location = $System_Drawing_Point
    $tabPageConsole.Name = "tabPageConsole" 
    $System_Windows_Forms_Padding = New-Object System.Windows.Forms.Padding
    $System_Windows_Forms_Padding.All = 3
    $System_Windows_Forms_Padding.Bottom = 3
    $System_Windows_Forms_Padding.Left = 3
    $System_Windows_Forms_Padding.Right = 3
    $System_Windows_Forms_Padding.Top = 3
    $tabPageConsole.Padding = $System_Windows_Forms_Padding
    $System_Drawing_Size = New-Object System.Drawing.Size
    $System_Drawing_Size.Height = 362
    $System_Drawing_Size.Width = 637
    $tabPageConsole.Size = $System_Drawing_Size
    $tabPageConsole.TabIndex = 2
    $tabPageConsole.Text = "Console"
    $tabPageConsole.UseVisualStyleBackColor = $True
        

    $tabControl1.Controls.Add($tabPageConsole)

    $RTB_Console.DataBindings.DefaultDataSourceUpdateMode = 0
    $System_Drawing_Point = New-Object System.Drawing.Point
    $System_Drawing_Point.X = 4
    $System_Drawing_Point.Y = 4
    $RTB_Console.Location = $System_Drawing_Point
    $RTB_Console.Name = "RTB_Console"
    $RTB_Console.ReadOnly = $true
    $System_Drawing_Size = New-Object System.Drawing.Size
    $System_Drawing_Size.Height = 352
    $System_Drawing_Size.Width = 627
    $RTB_Console.Size = $System_Drawing_Size
    $RTB_Console.TabIndex = 0
    $RTB_Console.Text = ""

    $tabPageConsole.Controls.Add($RTB_Console)
    #endregion Console Page
    
    #region OWA Unblock users
        
    $System_Drawing_Point = New-Object System.Drawing.Point
    $System_Drawing_Point.X = 4
    $System_Drawing_Point.Y = 22
    $tabPageOWAUnBlock.Location = $System_Drawing_Point
    $tabPageOWAUnBlock.Name = "tabPageUblock"
    $System_Windows_Forms_Padding = New-Object System.Windows.Forms.Padding
    $System_Windows_Forms_Padding.All = 3
    $System_Windows_Forms_Padding.Bottom = 3
    $System_Windows_Forms_Padding.Left = 3
    $System_Windows_Forms_Padding.Right = 3
    $System_Windows_Forms_Padding.Top = 3
    $tabPageOWAUnBlock.Padding = $System_Windows_Forms_Padding
    $System_Drawing_Size = New-Object System.Drawing.Size
    $System_Drawing_Size.Height = 362
    $System_Drawing_Size.Width = 637
    $tabPageOWAUnBlock.Size = $System_Drawing_Size
    $tabPageOWAUnBlock.Text = "OWA Spam Unblock"
    if ($env:isOWAConnected -eq "YES")
    {
        $tabControl1.Controls.Add($tabPageOWAUnBlock)
    }

    $System_Drawing_Point.X = 14
    $System_Drawing_Point.Y = 4
    $GB_BlockedUsers.Location = $System_Drawing_Point
    $GB_BlockedUsers.Text = "Currently Blocked Users"
    $System_Drawing_Size.Height = 301
    $System_Drawing_Size.Width = 614
    $GB_BlockedUsers.Size = $System_Drawing_Size
        
    $tabPageOWAUnBlock.Controls.Add($GB_BlockedUsers)


    $System_Drawing_Point.X = 6
    $System_Drawing_Point.Y = 18
    $DGV_BlockedUsers.Location = $System_Drawing_Point
    $System_Drawing_Size.Height = 277
    $System_Drawing_Size.Width = 602
    $DGV_BlockedUsers.Size = $System_Drawing_Size
    $DGV_BlockedUsers.ColumnCount = 2
    $DGV_BlockedUsers.Columns[0].Name = "Name"
    $DGV_BlockedUsers.Columns[1].Name = "Primary Smtp Address"
    $DGV_BlockedUsers.AutoSizeColumnsMode = "Fill"
    $DGV_BlockedUsers.RowHeadersVisible = $false
    $DGV_BlockedUsers.SelectionMode = "FullRowSelect"
    $DGV_BlockedUsers.AllowUserToAddRows = $false
    $DGV_BlockedUsers.EditMode = "EditProgrammatically"

    #Possiblity to implent a right click on table to remove user from block list
    $OWASearchBlock.Text = "Search Block List"
    $OWASearchBlock.Add_Click({
        $SearchForm = New-Object System.Windows.Forms.Form
        $GB_Search = New-Object System.Windows.Forms.GroupBox
        $TB_SearchBox = New-Object System.Windows.Forms.TextBox
        $BN_Search = New-Object System.Windows.Forms.Button
            

        $SearchForm.Text = "Search OWA Block List"
        $SearchForm.ShowIcon = $false
        $System_Drawing_Size.Height = 146
        $System_Drawing_Size.Width = 449
        $SearchForm.Size = $System_Drawing_Size
        $SearchForm.StartPosition = "CenterParent"
        $SearchForm.TopMost = $True
        $GB_Search.Text = "Search Block List"
        $GB_Search.Font = "Microsoft Sans Serif, 12pt"
        $System_Drawing_Point.X = 12
        $System_Drawing_Point.Y = 12
        $GB_Search.Location = $System_Drawing_Point
        $System_Drawing_Size.Height = 59
        $System_Drawing_Size.Width = 409
        $GB_Search.Size = $System_Drawing_Size

        $SearchForm.Controls.Add($GB_Search)

        $System_Drawing_Point.X = 6
        $System_Drawing_Point.Y = 25
        $TB_SearchBox.Location = $System_Drawing_Point
        $System_Drawing_Size.Height = 26
        $System_Drawing_Size.Width = 397
        $TB_SearchBox.Size = $System_Drawing_Size
        $TB_SearchBox.Add_KeyDown({
            if ($_.KeyCode -eq "Enter")
            {
                Search-DGV-BlockedUsers
                    
            }
        })
            
        $GB_Search.Controls.Add($TB_SearchBox)

        $BN_Search.Text = "Search"
        $System_Drawing_Point.X = 12
        $System_Drawing_Point.Y = 77
        $BN_Search.Location = $System_Drawing_Point
        $System_Drawing_Size.Height = 23
        $System_Drawing_Size.Width = 403
        $BN_Search.Size = $System_Drawing_Size

        function Search-DGV-BlockedUsers
        {
            for ($i = 0; $i -lt $DGV_BlockedUsers.RowCount; $i++)
            {
                $DGV_BlockedUsers.Rows[$i].Selected = $false
            }
            $invalidSearch = $True
            if ($TB_SearchBox.Text -like "*@ou.edu")
            {
                Write-Host "Email Search"
                for ($i = 0; $i -lt $DGV_BlockedUsers.RowCount; $i++)
                {
                    if ($DGV_BlockedUsers.Rows[$i].Cells[1].Value -eq $TB_SearchBox.Text)
                    {
                        $DGV_BlockedUsers.Rows[$i].Selected = $True
                        $DGV_BlockedUsers.FirstDisplayedScrollingRowIndex = $i
                        $SearchForm.Close()
                        $SearchForm.Dispose()
                        $invalidSearch = $false
                        break
                    }
                }
            }
            else
            {        
                for ($i = 0; $i -lt $DGV_BlockedUsers.RowCount; $i++)
                {
                    if ($DGV_BlockedUsers.Rows[$i].Cells[0].Value.Split(" ") -contains "$($TB_SearchBox.Text)")
                    {
                        $DGV_BlockedUsers.Rows[$i].Selected = $True
                        $DGV_BlockedUsers.FirstDisplayedScrollingRowIndex = $i
                        $SearchForm.Close()
                        $SearchForm.Dispose()
                        $invalidSearch = $false
                        break
                    }
                }
            }

            if ($invalidSearch)
            {
                [System.Windows.MessageBox]::Show("No User was found `n Search Query: `n $($TB_SearchBox.Text)", "Error", "Ok", "Error")
            }
        }

        $BN_Search.Add_Click({
            for ($i = 0; $i -lt $DGV_BlockedUsers.RowCount; $i++)
            {
                $DGV_BlockedUsers.Rows[$i].Selected = $false
            }
            $invalidSearch = $True
            if ($TB_SearchBox.Text -like "*@ou.edu")
            {
                Write-Host "Email Search"
                for ($i = 0; $i -lt $DGV_BlockedUsers.RowCount; $i++)
                {
                    if ($DGV_BlockedUsers.Rows[$i].Cells[1].Value -eq $TB_SearchBox.Text)
                    {
                        $DGV_BlockedUsers.Rows[$i].Selected = $True
                        $DGV_BlockedUsers.FirstDisplayedScrollingRowIndex = $i
                        $SearchForm.Close()
                        $SearchForm.Dispose()
                        $invalidSearch = $false
                        break
                    }
                }
            }
            else
            {        
                for ($i = 0; $i -lt $DGV_BlockedUsers.RowCount; $i++)
                {
                    if ($DGV_BlockedUsers.Rows[$i].Cells[0].Value.Split(" ") -contains "$($TB_SearchBox.Text)")
                    {
                        $DGV_BlockedUsers.Rows[$i].Selected = $True
                        $DGV_BlockedUsers.FirstDisplayedScrollingRowIndex = $i
                        $SearchForm.Close()
                        $SearchForm.Dispose()
                        $invalidSearch = $false
                        break
                    }
                }
            }

            if ($invalidSearch)
            {
                [System.Windows.MessageBox]::Show("No User was found `n Search Query: `n $($TB_SearchBox.Text)", "Error", "Ok", "Error")
            }
        })
        $SearchForm.Controls.Add($BN_Search)

        $SearchForm.ShowDialog()
    })
    $OWAUnblockContext.Items.Add($OWASearchBlock)

    $OWAUserUnblock.Add_Click({
        $selectedRows = $DGV_BlockedUsers.SelectedRows
        write-host "Remove Blocked Users"
        
        $i = 1
        $NumberOfSelctedRows = $selectedRows.Count
        $form1.Cursor = "WaitCursor"
        foreach ($row in $selectedRows)
        {
            $percent = ($i / $NumberOfSelctedRows) * 100
            Write-Progress -Activity "Removing Blocked Users" -Status "$percent% Complete" -PercentComplete $percent
            $DGV_BlockedUsers.Rows.RemoveAt($row.Index)
            Write-Host "$($row.Cells[0].Value) Email: $($row.Cells[1].Value)"
            Write-Host 'Remove-OWABlockedSenderAddress -SenderAddress' "$($row.Cells[1].Value)"
            Remove-OWABlockedSenderAddress -SenderAddress "$($row.Cells[1].Value)"
            $i++
        }
        $form1.Cursor = "Default"
        refresh_OWABlockedUsers
    })
    $OWAUserUnblock.Text = "Remove Block"
    $OWAUnblockContext.Items.Add($OWAUserUnblock)

    $DGV_BlockedUsers.ContextMenuStrip = $OWAUnblockContext

    $GB_BlockedUsers.Controls.Add($DGV_BlockedUsers)

    $blockedSenders = Get-OWABlockedSenderAddress

    foreach($sender in $blockedSenders)
    {
        $userMailbox = Get-OWAMailbox $sender.SenderAddress
        $name = $userMailbox.DisplayName.Split(",")
        $DGV_BlockedUsers.Rows.Add("$($name[1]) $($name[0])", "$($sender.SenderAddress)")
            
    }

    if ($env:isOWAConnected -eq "YES")
    {
        $unblockRefreshTimer = New-Object System.Windows.Forms.Timer

        $unblockRefreshTimer.Interval = 300000
        $unblockRefreshTimer.Add_Tick({
            Write-Host "Refreshed OWA Blocked Users List"
            refresh_OWABlockedUsers
        })
    }

    #endregion
    #endregion Generated Form Code

    $form1.add_shown({
        #TODO UNCOMMENT
        $unblockRefreshTimer.Start()
    })

    #Save the initial state of the form
    $InitialFormWindowState = $form1.WindowState
    #Init the OnLoad event to correct the initial state of the form
    $form1.add_Load($OnLoadForm_StateCorrection)
    $form1.Add_FormClosed({
        $loginForm.Visible = $True
        $sessions = Get-PSSession 
        $sessions | Remove-PSSession
        $form1.Dispose()
    })
    #Show the Form
    $form1.ShowDialog()| Out-Null

} #End Function

function updateConsole {
    $RTB_Console.Select($RTB_DLOutput.Text.Length, 0)
    $RTB_Console.ScrollToCaret()
    $form1.Update()
}

function updateDLOutput {
    $RTB_DLOutput.Select($RTB_DLOutput.Text.Length, 0)
    $RTB_DLOutput.ScrollToCaret()
    $form1.Update()
}

function updateMBPOutput {
    $RTB_MBP_Output.Select($RTB_MBP_Output.Text.Length, 0)
    $RTB_MBP_Output.ScrolltoCaret()
    $form1.Update()
}

function updateUnblockOutput {
    $RTB_UnblockConsole.Select($RTB_UnblockConsole.Text.Length, 0)
    $RTB_UnblockConsole.ScrollToCaret()
    $form1.Update()
}


function updateServers {
    $form1.Update()
}

function encryptPassword ($unecrypted) {
    if (Test-Path $keyFile)
    {
        $key = get-content $keyFile
        $passUncrypted = ConvertTo-SecureString -String $unecrypted -AsPlainText -Force
        $encrypted = ConvertFrom-SecureString $passUncrypted -Key $key

        return $encrypted
    }
    else
    {
        $key = New-Object Byte[] 32
        [Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($key)
        $key | Out-File $keyFile

        encryptPassword($unecrypted)
    }
}

function create-session ($user, $password, $serverType, $serverId)
{
    if ($serverType -eq "Office 365")
    {
        #Create a PScred to sign in to the specified server Type
        $cred = New-Object System.Management.Automation.PSCredential -ArgumentList $user, ($password | ConvertTo-SecureString -Key (Get-Content $keyFile))
        try{
            $session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $cred -Authentication Basic -Name "$($serverType)" -AllowRedirection
            return $session
        } catch
        {
            $errorString = $_.Exception.Message
            [System.Windows.MessageBox]::Show("$($errorString)", "Error", "Ok", "Error")
            return $null
        }
    }

    if ($serverType -eq "Local Exchange")
    {
        #Create a PScred to sign in to the specified server Type
        $cred = New-Object System.Management.Automation.PSCredential -ArgumentList $user, ($password | ConvertTo-SecureString -Key (Get-Content $keyFile))
        try {
            #Write-EventLog '$session = New-PSession -ConfigurationName Microsoft.Exchange -ConnectionUri `"LocalServerAddress" -Authentication Kerberos -Credential $cred'
            $session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "http://$($env:LocalServerAddress)/Powershell" -Authentication Kerberos -Credential $cred -Name "$($serverType)"
            return $session
        } catch
        {
            [System.Windows.MessageBox]::Show("$($errorString)", "Error", "Ok", "Error")
            return $null
        }
    }
}

function add-server
{
    #region elements
    $addServerForm = New-Object System.Windows.Forms.Form
    $addServerForm.Size = New-Object System.Drawing.Size(352, 174)
    $usnLBL = New-Object System.Windows.Forms.Label
    $usnText = New-Object System.Windows.Forms.TextBox
    $passLBL = New-Object System.Windows.Forms.Label
    $TB_passWD = New-Object System.Windows.Forms.TextBox
    $SelectLabel = New-Object System.Windows.Forms.Label
    $option = New-Object System.Windows.Forms.ComboBox
    $submit = New-Object System.Windows.Forms.Button

    $addServerForm.FormBorderStyle = "FixedSingle"
    $addServerForm.Text = "Add Server"
    $addServerForm.StartPosition = "CenterParent"

    $usnLBL.Size = New-Object System.Drawing.Size(92, 22)
    $usnLBL.location = New-Object System.Drawing.Size(14,13)
    $usnLBL.Text = "Username"
    $usnLBL.Font ="Microsoft Sans Serif, 13"
    #$usnLBL.Font.Size = 13
    $addServerForm.Controls.Add($usnLBL)
    
    $usnText.Size = New-Object System.Drawing.Size(198, 20)
    $usnText.Location = New-Object System.Drawing.Size(112, 15)
    $usnText.Add_Leave({
        if ($usnText.Text -like "*@sooners.onmicrosoft.com")
        {
            $option.SelectedIndex = 1
            return
        }
        $lowerCase = ("$($env:Domain)").ToLower
        $upperCase = ("$($env:Domain)").ToUpper
        if ($usnText.Text.Contains("$lowerCase\") -or ($usnText.Text.Contains("$upperCase\")))
        {
            $option.SelectedIndex = 0
            return
        }
        else {
            $usnText.Text = "$($env:Domain)\$($usnText.Text)"
            $option.SelectedIndex = 0
            return
        }
    })
    $addServerForm.Controls.Add($usnText)

    $passLBL.Size = New-Object System.Drawing.Size(89, 22)
    $passLBL.Location = New-Object System.Drawing.Size(14, 45)
    $passLBL.Text = "Password"
    $passLBL.Font ="Microsoft Sans Serif, 13"
    #$passLBL.Font.Size = 13
    $addServerForm.Controls.Add($passLBL)

    $TB_passWD.Size = New-Object System.Drawing.Size(198, 20)
    $TB_passWD.Location = New-Object System.Drawing.Size(112, 46)
    $TB_passWD.UseSystemPasswordChar = $True
    $TB_passWD.Add_Leave({
        if ($TB_passWD.Text.Length -gt 0)
        {
            $submit.Enabled = $True
        }
    })
    $addServerForm.Controls.Add($TB_passWD)

    $SelectLabel.Size = New-Object System.Drawing.Size(159, 22)
    $SelectLabel.Location = New-Object System.Drawing.Size(14, 81)
    $SelectLabel.Text = "Please Select One"
    $SelectLabel.Font ="Microsoft Sans Serif, 13"
    #$SelectLabel.Font.Size = 13
    $addServerForm.Controls.Add($selectLabel)

    #[xml] $configDoc = Get-Content $con

    $option.Items.Add("Local Exchange")
    $option.Items.Add("Office 365")
    $option.Location = New-Object System.Drawing.Size(179, 81)
    $option.Size = New-Object System.Drawing.Size(131, 21)
    $addServerForm.Controls.Add($option)
    
    $option.Add_SelectedIndexChanged({
        Switch($option.SelectedIndex)
        {
            1 {
                $optionValue = $option.Text
            }
            2 {
                $optionValue = $option.Text
            }
        }
    })

    $submit.Size = New-Object System.Drawing.Size(75, 23)
    $submit.Location = New-Object System.Drawing.Size(235, 108)
    $submit.Text = "Submit"
    $submit.Enabled = $false
    #endregion

    $submit.Add_Click({
        $pass = "$($TB_passWD.Text)"
        $password = encryptPassword -unecrypted $pass
        if ($password)
        {
            [xml] $configDoc = Get-Content $configFile

            [System.XML.XMLElement] $server = $configDoc.CreateElement("Server")
            $server.SetAttribute("name", $option.Text)
            $ids = $configDoc.SelectNodes("//Server").id
            if($ids)
            {
                for ($i = 1; $i -le ($ids.Count + 1); $i++)
                {
                    if (!($ids.Contains($i)))
                    {
                        $server.SetAttribute("id", ($i))
                    }
                }
            } else {
                $server.SetAttribute("id", (1))
            }
            if ($option.Text -eq "Local Exchange")
            {
                $server.SetAttribute("Resource", "$($env:LocalServerAddress)")
                $resource = "$($env:LocalServerAddress)"
            }
            else
            {
                $server.SetAttribute("Resource", "Office 365")
                $resource = "Office 365"
            }
        
            [System.XML.XMLElement] $user = $configDoc.CreateElement("User")
            $user.InnerText = $usnText.Text
        

            $server.AppendChild($user)

            $configDoc.SelectSingleNode("Servers").appendChild($server)

            $configDoc.Save($configFile)
            $cred = New-Object Windows.Security.Credentials.PasswordCredential -ArgumentList $resource, "$($usnText.Text)", $password
            $vault.Add($cred)
        
            $usnText.Clear()
            $TB_passWD.Clear()
        
            $serverGridView.Rows.Clear()

            foreach($node in $configDoc.SelectNodes("//Server")){
                $id = $node.id
                $userName = $node.User
                $ServerType = $node.name
                
                $serverGridView.Rows.Add($id, $userName, "False", $ServerType)
            }
            $addServerForm.Close()
        }
    })
    $addServerForm.Controls.Add($submit)


        $addServerForm.Add_Shown({
            $addServerForm.Activate()
        })
        $addServerForm.Add_FormClosed({
            
        })
        [void] $addServerForm.ShowDialog()

}

function install-SCGUI
{
    setSessionLogLocation -location "C:\ProgramData\SCGUI\logs.xml"
    #Creates Registry Keys
    if (!(Test-Path "$($key)\SCGUI"))
    {
        New-Item  -Path $key -Name "SCGUI"
        New-ItemProperty -Path "$($key)\SCGUI" -Name "Installed" -Value "False"
    }
    $value = Get-ItemProperty -Path "$($key)\SCGUI"
    #Creates Folders
    if(!(Test-Path "$($directory)\assets\help"))
    {
        New-Item -ItemType Directory -Force -Path "$($directory)\assets\help"

        $htmlDocument = {
            "<html>
            <head>
            </head>
            <body>
            <h3> How to add and Delete Server </h3>
            <h6> Adding Servers </h6>
 
            <p> 1. To Add a server start by clicking add server in the menu bar. This will then present you with a dialog to add the server with credentials.
            </br> 2. Enter your credentials and select the server type or enter the server name, then click add.
            </p>
 
            <h6> Deleting a server </h6>
            <p> To Delete a server you must right click the selected row and choose delete on the tooltip it presents you. Make sure you have the row you want to delete selected otherwise you will delete the currently selected row. For Example if you have two rows and you want to delete the first one, but the second row is highlighted and you choose to delete. You will delete the second row. This only deletes the currently selected row.
            </p>
            </body>
            </html>
            "

        }
        $htmlDocument | Out-File "$($directory)\assets\help\server.html"
    }
    if(!(Test-Path "$($exportDirectory)"))
    {
        New-Item -ItemType Directory -Force -Path "$($exportDirectory)"
        New-Item -ItemType Directory -Force -Path "$($exportDirectory)\CSV"
        New-Item -ItemType Directory -Force -Path "$($exportDirectory)\XML"
    }
    if (!(Test-Path "C:\ProgramData\SCGUI"))
    {
        New-Item -ItemType Directory -Force -Path "C:\ProgramData\SCGUI"
    }

    if (!(Test-Path "C:\ProgramData\SCGUI\settings.xml"))
    {
        [System.XML.XMLDocument] $SettingDocument = New-Object System.XML.XMLDocument
        [System.XML.XMLElement] $settings = $SettingDocument.CreateElement("Settings")
        $settings.SetAttribute("Description", "Contains a list of all active settings for the SCGUI Application.")
        $SettingObject = $SettingDocument.CreateElement("Setting")
        
        $DomainElement = $SettingDocument.CreateElement("Domain")
        $DomainElement.InnerText = ""
        $SettingObject.AppendChild($DomainElement)

        $LocalExchangeElement = $SettingDocument.CreateElement("LocalExchangeAddress")
        $LocalExchangeElement.InnerText = ""
        $SettingObject.AppendChild($LocalExchangeElement)

        $logElement = $SettingDocument.CreateElement("LogLocation")
        $logElement.InnerText = "$($env:sessionLogLocation)"
        $SettingObject.AppendChild($logElement)
        
        $adminElement = $SettingDocument.CreateElement("AdminGroup")
        $adminElement.InnerText = ""
        $SettingObject.AppendChild($adminElement)

        $userElement = $SettingDocument.CreateElement("UsersGroup")
        $userElement.InnerText = ""
        $SettingObject.AppendChild($userElement)

        $settings.AppendChild($SettingObject)
        $SettingDocument.AppendChild($settings)
        save-settingsLog -log $SettingDocument
    }
    #Checks Registry key to verify if program has ran through the install form
    if ($value.Installed -eq "False")
    {
        GenerateInstallForm
        Set-ItemProperty -Path "$($key)/SCGUI" -Name "Installed" -Value "True"
    }

    Write-Host "Version: $($value.Version)"
}
function create-SessionLog([xml] $sessionLog)
{
    $random = Get-Random -Minimum 0 -Maximum 99999
    $sessionID = "$($env:USERNAME)$($random)"
    if ($sessionLog.HasChildNodes)
    {
        while ($sessionLog.SelectSingleNode("/Sessions/Session[@SessionID=$($sessionID)]"))
        {
            $random = Get-Random -Minimum 0 -Maximum 99999
            $sessionID = "$($env:USERNAME)$($random)" 
        }
    }
    set-SessionID -id $sessionID
    #Write-Host $env:sessionID
    [System.XML.XMLElemnt] $element = $sessionLog.CreateElement("Session")
    $element.SetAttribute("User", $env:USERNAME)
    $element.SetAttribute("Date", (Get-Date -Format g))
    $element.SetAttribute("SessionID", $sessionID)

    return $element
}
function add-ActionElementToSessionLog($action, $oldValue, $newValue)
{
    $actionElement = $sessionLog.CreateElement("Action")
    $actionElement.SetAttribute("ActionType",$action)
    if ($oldValue)
    {
        $actionElement.SetAttribute("OldValue", $oldValue)
    }
    if ($newValue)
    {
        $actionElement.SetAttribute("NewValue",$newValue)
    }

    return $actionElement
}
function add-actionDetails($detailTitle,$detailExplanation, $errorcode = $null, [System.XML.XMLElement] $actionElement)
{
    $actionDetail = $sessionLog.CreateElement("ActionDetail")
    $actionDetail.SetAttribute("Detail",$detailTitle)
    $actionDetail.SetAttribute("Information", $detailExplanation)
    $actionDetail.SetAttribute("Date", (Get-Date).ToUniversalTime())
    if ($errorcode)
    {
        $actionDetail.SetAttribute("ErrorCode", $errorcode)
    }
    
    $actionElement.AppendChild($actionDetail)
    
}
function save-actionElementToSessionLog($element)
{
    $sessionElement.AppendChild($element)
}

function save-sessionLog([xml] $log, $element = $null)
{
    if($element)
    {
        $sessionLog.FirstChild.AppendChild($element)

        save-sessionLog($sessionLog)
    }
    $log.Save("$($env:sessionLogLocation)")
}
function save-settingsLog([xml] $log)
{
    $log.Save("C:\ProgramData\SCGUI\Settings.xml")
}

function GenerateLoginPage ()
{
    $loginForm.Size = new-object System.Drawing.Size(502, 400)
    $loginForm.ShowIcon = $false
    $loginForm.MinimizeBox = $false
    $loginForm.MaximizeBox = $false
    $loginForm.StartPosition = "CenterScreen"
    $loginForm.Icon = "C:\Program Files\Common Files\server_earth_aTu_icon.ico"
    $loginForm.ShowIcon = $True
    #$loginForm.Icon = [System.Drawing.Icon]::ExtractAssociatedIcon('C:\Program Files\Common Files\server_earth_aTu_icon.ico')

    $menuBar = New-Object System.Windows.Forms.MenuStrip

    $addServer = New-Object System.Windows.Forms.ToolStripMenuItem
    $addServer.Text = "Add Account"
    $addServer.Add_Click({
    add-server
    })

    $menuBar.Items.Add($addServer)

    $connectOne = New-Object System.Windows.Forms.ToolStripMenuItem
    $connectOne.Text = "Start Program"
    $connectOne.ToolTipText = "To Start the program you must have added 2 Servers. `n 1. Office 365`n 2. Local Exchange"
    $connectOne.Add_Click({
        [xml] $configXML = Get-Content $configFile
        foreach($node in $configXML.SelectNodes("//Server"))
        {
            $id = $node.id
            $userName = $node.User
            $serverType = $node.name
            $resource = $node.Resource
            $cred = $vault.Retrieve($resource, $userName)
            $pass = $cred.Password
        
            $notifyIcon.ShowBalloonTip(20000, "Connecting", "Trying to connect", "Info")

            if ($serverType -eq "Local Exchange")
            {
                $session = create-session -user $userName -password $pass -serverType $serverType -serverId $id
                if($session)
                {
                    $action = add-ActionElementToSessionLog -action "Local Exchange Server Connection" -oldValue "False" -newValue "True" -sessionElement $sessionElement
                    save-actionElementToSessionLog -element $action
                    save-sessionLog -log $sessionLog -element $sessionElement
                    Import-PSSession $session -Prefix Local
                    set-isLocalConnected -value "YES"
                    $notifyIcon.ShowBalloonTip(5000, "Connected to $serverType", "You are now connected to $serverType", "Info")
                }
                else
                {
                    $action = add-ActionElementToSessionLog -action "Local Exchange Server Connection Error" -oldValue "False" -newValue "False" -sessionElement $sessionElement
                    save-actionElementToSessionLog -element $action
                    save-sessionLog -log $sessionLog -element $sessionElement
                }
            }
            if ($serverType -eq "Office 365")
            {
                $session = create-session -user $userName -password $pass -serverType $serverType -serverId $id
                if ($session)
                {
                    $action = add-ActionElementToSessionLog -action "O365 Connection" -oldValue "False" -newValue "True" -sessionElement $sessionElement
                    save-actionElementToSessionLog -element $action
                    save-sessionLog -log $sessionLog -element $sessionElement
                    Import-PSSession $session -Prefix OWA
                    set-isOWAConnected -value "YES"
                    $notifyIcon.ShowBalloonTip(5000, "Connected to $serverType", "You are now connected to $serverType", "Info")
                }
                else
                {
                    $action = add-ActionElementToSessionLog -action "O365 Connection Error" -oldValue "False" -newValue "False" -sessionElement $sessionElement
                    save-actionElementToSessionLog -element $action
                    save-sessionLog -log $sessionLog -element $sessionElement
                }
            }
        }
        if ($env:isOWAConnected -eq "NO" -or $env:isLocalConnected -eq "NO")
        {
            if ($env:isOWAConnected -eq "NO")
            {
                $OWAStatus = "False"
            } else
            {
                $OWAStatus = "True"
            }
            if ($env:isLocalConnected -eq "NO")
            {
                $localStatus = "False"
            } else {
                $localStatus = "True"
            }
            [System.Windows.MessageBox]::Show("Connection Status:`n Local Exchange: $localStatus`n Office 365 Status: $OWAStatus `n Some function may be unavailable until connection is made to the missing server.", "Warning", "Ok", "Warning")
        }
        $loginForm.Visible = $false
        GenerateForm
    })

    $menuBar.Items.Add($connectOne)

    $adminBar = New-Object System.Windows.Forms.ToolStripMenuItem
    $adminBar.Text = "Admin Panel"
    $adminBar.Add_Click({
        $adminLoginAction = add-ActionElementToSessionLog -action "User Logged into Admin Panel"
        save-actionElementToSessionLog -element $adminLoginAction
        save-sessionLog -log $sessionLog -element $sessionElement
        GenerateAdminPanel
    })

    $admins = Get-ADGroupMember "$($env:AdminGroup)"
    $user = Get-ADUser $env:USERNAME
    foreach ($admin in $admins)
    {
        if ($admin.distinguishedName -eq "$($user.DistinguishedName)")
        {
            $menuBar.Items.Add($adminBar)
        }
    }

    $loginForm.Controls.Add($menuBar)

    $serverGridView = New-Object System.Windows.Forms.DataGridView
    $serverGridView.Size = New-Object System.Drawing.Size(486, 333)
    $serverGridView.Location = New-Object System.Drawing.Size(0, 27)

    $serverGridView.ColumnCount = 4
    $serverGridView.ColumnHeadersVisible = $True
    $serverGridView.Columns[0].Name = "ID"
    $serverGridView.Columns[1].Name = "Exchange User"
    $serverGridView.Columns[2].Name = "Connected"
    $serverGridView.Columns[3].Name = "Type"
    #$serverGridView.AutoSize = $true
    $serverGridView.ScrollBars = "Vertical"
    $serverGridView.AllowUserToAddRows = $false
    $serverGridView.RowHeadersVisible = $false
    $serverGridView.Columns[0].Width = 50
    $serverGridView.Columns[1].Width = 261
    $serverGridView.Columns[2].Width = 75
    $serverGridView.Columns[3].Width = 100



    $contextMenu = New-Object System.Windows.Forms.ContextMenuStrip

    #$connect = New-Object System.Windows.Forms.ToolStripMenuItem
    #$connect.Text = "Connect to"
    $delete = New-Object System.Windows.Forms.ToolStripMenuItem
    $delete.Text = "Delete Server"

    $delete.Add_Click({
        $index = $serverGridView.CurrentRow.Cells[0].Value
        [XML] $configXML = Get-Content $configFile
        $node = $configXML.SelectSingleNode("/Servers/Server[@id=$($index)]")
    
        try {
            $node.ParentNode.RemoveChild($node)
            $serverGridView.Rows.RemoveAt($serverGridView.CurrentRow.Index)
            $resource = "$($node.Resource)"
            $user = "$($node.User)"
            $vault.Remove($vault.Retrieve($resource, $user))
            $configXML.Save($configFile)
            
        } catch
        {
            Write-Host "Alert User of an Error"
        }
        $loginForm.Update()
    })

    #$contextMenu.Items.Add($connect)
    $contextMenu.Items.Add($delete)
    $serverGridView.ContextMenuStrip = $contextMenu
    $loginForm.Controls.Add($serverGridView)

    if(!(Test-Path $configFile))
    {    
            New-Item -ItemType Directory -Force -Path "$directory"
            New-Item -ItemType Directory -Force -Path "$($directory)\assets"
            New-Item -ItemType Directory -Force -Path "$($directory)\assets\security"
        [System.XML.XMLDocument] $configDocument = New-Object System.XML.XMLDocument
        [System.XML.XMLElement] $serverElement = $configDocument.CreateElement("Servers")
        $configDocument.AppendChild($serverElement)
        $serverElement.SetAttribute("Description", "List of servers with saved credentials.")

        $configDocument.Save($configFile)

        $acl = Get-Acl -Path "$($directory)\assets\security"
        $perm = "$($env:USERDNSDOMAIN)\$($env:USERNAME)", 'FullControl', 'ContainerInherit, ObjectInherit', 'None', 'Allow'
        $rule = New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $perm
        $acl.SetAccessRuleProtection($true, $false)
        $acl.RemoveAccessRule($rule)
        $acl.AddAccessRule($rule)
        $perm2 = "Administrators", 'CreateFiles, Write, Read', 'ContainerInherit, ObjectInherit', 'None', 'Allow'
        $rule2 = New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $perm2
        $acl.AddAccessRule($rule2)
        $acl | Set-Acl -Path "$($directory)\assets\security"
    }

    [xml] $configF = Get-Content $configFile


    foreach($node in $configF.SelectNodes("//Server")){
        $id = $node.id
        $userName = $node.User
        $ServerType = $node.name
        $serverGridView.Rows.Add($id, $userName, "False", $ServerType)
    }

    $loginForm.add_FormClosing({
        Write-Host "Form is Closing"
        [xml] $log = Get-Content $env:sessionLogLocation
        #TODO XML LOG
        save-sessionLog -log ($log)
    })
    $loginForm.ShowDialog() | Out-Null
}
function GenerateAdminPanel()
{
    #region Form Objects
    $adminPanelForm = New-Object System.Windows.Forms.Form
    $MenuBar = New-Object System.Windows.Forms.MenuStrip
    $preferencesToolbar = New-Object System.Windows.Forms.ToolStripMenuItem
    $settingsToolbar = New-Object System.Windows.Forms.ToolStripMenuItem

    #region GroupBox Admins
    $GB_Admins = New-Object System.Windows.Forms.GroupBox
    $ContextMenuAdmin = New-Object System.Windows.Forms.ContextMenuStrip
    $Add_Admins = New-Object System.Windows.Forms.ToolStripMenuItem
    $Remove_Admins = New-Object System.Windows.Forms.ToolStripMenuItem
    $DGV_Admins = New-Object System.Windows.Forms.DataGridView
    #endregion

    #region GroupBox Users
    $GB_Users = New-Object System.Windows.Forms.GroupBox
    $ContextMenu = New-Object System.Windows.Forms.ContextMenuStrip
    $Add_Users = New-Object System.Windows.Forms.ToolStripMenuItem
    $Remove_Users = New-Object System.Windows.Forms.ToolStripMenuItem
    $DGV_Users = New-Object System.Windows.Forms.DataGridView
    #endregion

    #region GroupBox Logs
    $GB_Logs = New-Object System.Windows.Forms.GroupBox
    $CMS_UserSort = New-Object System.Windows.Forms.ContextMenuStrip
    $TB_UserSort = New-Object System.Windows.Forms.TextBox
    $LB_FromDate = New-Object System.Windows.Forms.Label
    $DTP_FromDate = New-Object System.Windows.Forms.DateTimePicker
    $LB_EndDate = New-Object System.Windows.Forms.Label
    $DTP_EndDate = New-Object System.Windows.Forms.DateTimePicker
    $DGV_Sessions = New-Object System.Windows.Forms.DataGridView
    $GB_Actions = New-Object System.Windows.Forms.GroupBox
    $GB_ActionDetails = New-Object System.Windows.Forms.GroupBox
    $DGV_Actions = New-Object System.Windows.Forms.DataGridView
    $DGV_ActionDetails = New-Object System.Windows.Forms.DataGridView
    $BTN_ResetSearch = New-Object System.Windows.Forms.Button

    #endregion
    #region Size and location variable
    $system_drawing_size = New-Object System.Drawing.Size
    $system_drawing_point = New-Object System.Drawing.Point
    #endregion

    #endregion

    #region Design Form
    $system_drawing_size.Height = 900
    $system_drawing_size.Width = 900
    $adminPanelForm.Size = $system_drawing_size
    $adminPanelForm.StartPosition = "CenterParent"
    $adminPanelForm.Text = "SCGUI Admin"
    $adminPanelForm.TopMost = $false
    $adminPanelForm.BackColor = "Silver"
    $adminPanelForm.ShowIcon = $True
    $adminPanelForm.Icon = "C:\Program Files\Common Files\139500_200_rOu_icon.ico"
    $adminPanelForm.Controls.Add($MenuBar)

    $preferencesToolbar.Text = "Preferences"
    
    $settingsToolbar.Text = "Settings"
    $settingsToolbar.Add_Click({
        $SettingForm = New-Object System.Windows.Forms.Form
        $DGV_PropertyGrid = New-Object System.Windows.Forms.DataGridView
        $system_drawing_size.Height = 298
        $system_drawing_size.Width = 391
        $SettingForm.Size = $system_drawing_size
        $SettingForm.Text = "Settings"
        $SettingForm.StartPosition = "CenterParent"
        $SettingForm.FormBorderStyle = "FixedSingle"
        $SettingForm.TopMost = $True

        $system_drawing_point.X = 1
        $system_drawing_point.Y = 1
        $DGV_PropertyGrid.Location = $system_drawing_point
        $system_drawing_size.Height = 257
        $system_drawing_size.Width = 371
        $DGV_PropertyGrid.Size = $system_drawing_size

        $DGV_PropertyGrid.ColumnCount = 2
        $DGV_PropertyGrid.Columns[0].Name = "Property"
        $DGV_PropertyGrid.Columns[0].ReadOnly = $True
        $DGV_PropertyGrid.Columns[1].Name = "Value"
        $DGV_PropertyGrid.AutoSizeColumnsMode = "Fill"

        $DGV_PropertyGrid.RowHeadersVisible = $false
        $DGV_PropertyGrid.Rows.Add("Domain","")
        $DGV_PropertyGrid.Rows.Add("Local Exchange Address", "")
        $DGV_PropertyGrid.Rows.Add("Log Location", "")
        $DGV_PropertyGrid.Rows.Add("Admin Group", "")
        $DGV_PropertyGrid.Rows.Add("Users Group","")
        $DGV_PropertyGrid.AllowUserToAddRows = $false
        $DGV_PropertyGrid.AllowUserToOrderColumns = $false
        $DGV_PropertyGrid.SelectionMode = "FullRowSelect"

        $DGV_PropertyGrid.Add_CellEndEdit({
            Modify_Settings -settingObject ($DGV_PropertyGrid.SelectedRows.Cells[0].Value) -value ($DGV_PropertyGrid.SelectedRows.Cells[1].Value)

        })

        $SettingForm.Controls.Add($DGV_PropertyGrid)
        
        $SettingForm.Add_Load({
            Load_Settings -propertyGrid $DGV_PropertyGrid
        })

        $SettingForm.ShowDialog() | Out-Null
    })
    $preferencesToolbar.DropDownItems.Add($settingsToolbar)
    $MenuBar.Items.Add($preferencesToolbar)

    $GB_Admins.Text = "Admins"
    $system_drawing_point.X = 12
    $system_drawing_point.Y = 42
    $GB_Admins.Location = $system_drawing_point
    $system_drawing_size.Height = 193
    $system_drawing_size.Width = 429
    $GB_Admins.Size = $system_drawing_size
    
    $adminPanelForm.Controls.Add($GB_Admins)

    $system_drawing_point.X = 6
    $system_drawing_point.Y = 19
    $DGV_Admins.Location = $system_drawing_point
    $system_drawing_size.Width = 410
    $system_drawing_size.Height = 168
    $DGV_Admins.Size = $system_drawing_size
    $DGV_Admins.ColumnCount = 3
    $DGV_Admins.Columns[0].Name = "4x4"
    $DGV_Admins.Columns[1].Name = "Name"
    $DGV_Admins.Columns[2].Name = "UPN"
    $DGV_Admins.AutoSizeColumnsMode = "Fill"
    $DGV_Admins.AllowUserToAddRows = $false
    $DGV_Admins.AllowUserToDeleteRows = $false
    $DGV_Admins.RowHeadersVisible = $false
    $DGV_Admins.SelectionMode = "FullRowSelect"

    $Add_Admins.Text = "Add Admin"
    $Add_Admins.Add_Click({
        Modify-Users -method "Add" -group "$($env:AdminGroup)"
    })

    $ContextMenuAdmin.Items.Add($Add_Admins)

    $Remove_Admins.Text = "Remove Admin"
    $Remove_Admins.Add_Click({
        Modify-Users -method "Remove" -user "$($DGV_Admins.SelectedRows.Cells[0].Value)" -group "$($env:AdminGroup)"
    })
    $ContextMenuAdmin.Items.Add($Remove_Admins)

    $DGV_Admins.ContextMenuStrip = $ContextMenuAdmin
    

    $GB_Admins.Controls.Add($DGV_Admins)

    $system_drawing_point.X = 447
    $system_drawing_point.Y = 42
    $GB_Users.Location = $system_drawing_point
    $system_drawing_size.Height = 193
    $system_drawing_size.Width = 429
    $GB_Users.Size = $system_drawing_size
    $GB_Users.Text = "Users"
    
    $adminPanelForm.Controls.Add($GB_Users)

    $system_drawing_point.X = 6
    $system_drawing_point.Y = 19
    $DGV_Users.Location = $system_drawing_point
    $system_drawing_size.Width = 410
    $system_drawing_size.Height = 168
    $DGV_Users.Size = $system_drawing_size
    $DGV_Users.ColumnCount = 3
    $DGV_Users.Columns[0].Name = "4x4"
    $DGV_Users.Columns[1].Name = "Name"
    $DGV_Users.Columns[2].Name = "UPN"
    $DGV_Users.AutoSizeColumnsMode = "Fill"
    $DGV_Users.RowHeadersVisible = $false
    $DGV_Users.AllowUserToAddRows = $false
    $DGV_Users.AllowUserToDeleteRows = $false
    $DGV_Users.SelectionMode = "FullRowSelect"
    
    $users = Get-ADGroupMember "$($env:UsersGroup)"

    foreach ($user in $users)
    {
        $userObject = Get-ADUser "$($user.distinguishedName)"
        if ($userObject)
        {
            $DGV_Users.Rows.Add("$($userObject.SamAccountName)", "$($userObject.Name)", "$($userObject.UserPrincipalName)")
        }
    }

    $Add_Users.Text = "Add User"
    $Add_Users.Add_Click({
        Modify-Users -method "Add" -group "$($env:UsersGroup)"
    })

    $ContextMenu.Items.Add($Add_Users)

    $Remove_Users.Text = "Remove User"
    $Remove_Users.Add_Click({
        Modify-Users -method "Remove" -user "$($DGV_Users.SelectedRows.Cells[0].Value)" -group "$($env:UsersGroup)"
    })

    $ContextMenu.Items.Add($Remove_Users)

    $DGV_Users.ContextMenuStrip = $ContextMenu
    $GB_Users.Controls.Add($DGV_Users)

    $system_drawing_point.X = 12
    $system_drawing_point.Y = 241
    $GB_Logs.Location = $system_drawing_point
    $system_drawing_size.Height = 608
    $system_drawing_size.Width = 861
    $GB_Logs.Size = $system_drawing_size
    $GB_Logs.Text = "Session Logs"

    $adminPanelForm.Controls.Add($GB_Logs)

    $TB_UserSort.Text = "User Filter"
    $system_drawing_point.X = 6
    $system_drawing_point.Y = 25
    $TB_UserSort.Location = $system_drawing_point
    $system_drawing_size.Height = 20
    $system_drawing_size.Width = 140
    $TB_UserSort.Size = $system_drawing_size
    $TB_UserSort.Add_Click({
        $TB_UserSort.Text = ""
        $userContext = New-Object System.Windows.Forms.ContextMenuStrip
        [xml] $userLog = Get-Content "$($env:sessionLogLocation)"
        $nodes = $userLog.SelectNodes("/Sessions/Session")
        [System.Collections.ArrayList] $UserArray = New-Object System.Collections.ArrayList
        foreach ($node in $nodes)
        {
            if (!($UserArray.Contains("$($node.User)")))
            {
                $UserArray.Add("$($node.User)")
            }
        }
        for ($i = 0; $i -lt $UserArray.Count; $i++)
        {
            $userContext.Items.Add("$($UserArray[$i])", $null, {
                $TB_UserSort.Text = "$($this.Text)"
                $TB_UserSort.SelectNextControl($TB_UserSort, $true, $false, $false, $false)
            })
        }

        $system_drawing_point.X = 0
        $system_drawing_point.Y = 0
        $userContext.Show($TB_UserSort, $system_drawing_point)

    })
    $TB_UserSort.Add_Leave({
        if ($TB_UserSort.Text.Length -eq 0)
        {
            $TB_UserSort.Text = "User Filter"
            return
        }
        if ($TB_UserSort.Text.Length -gt 0)
        {
            sort-sessionLog
        }
    })

    $GB_Logs.Controls.Add($TB_UserSort)

    $system_drawing_point.X = 152
    $system_drawing_point.Y = 28
    $LB_FromDate.Location = $system_drawing_point
    $system_drawing_size.Height = 13
    $system_drawing_size.Width = 55
    $LB_FromDate.Size = $system_drawing_size
    $LB_FromDate.Text = "Start Date:"

    $GB_Logs.Controls.Add($LB_FromDate)

    $system_drawing_point.X = 213
    $system_drawing_point.Y = 25
    $DTP_FromDate.Location = $system_drawing_point
    $system_drawing_size.Height = 20
    $system_drawing_size.Width = 203
    $DTP_FromDate.Size = $system_drawing_size
    $DTP_FromDate.ShowCheckBox = $True
    $DTP_FromDate.Checked = $false

    $DTP_FromDate.Add_ValueChanged({
        if ($DTP_FromDate.Checked -and $DTP_EndDate.Checked)
        {
            sort-sessionLog
        }
    })

    $GB_Logs.Controls.Add($DTP_FromDate)

    $system_drawing_point.X = 422
    $system_drawing_point.Y = 25
    $LB_EndDate.Location = $system_drawing_point
    $system_drawing_size.Height = 13
    $system_drawing_size.Width = 55
    $LB_EndDate.Size = $system_drawing_size
    $LB_EndDate.Text = "End Date:"

    $GB_Logs.Controls.Add($LB_EndDate)

    $system_drawing_point.X = 480
    $system_drawing_point.Y = 25
    $DTP_EndDate.Location = $system_drawing_point
    $system_drawing_size.Height = 20
    $system_drawing_size.Width = 203
    $DTP_EndDate.Size = $system_drawing_size
    $DTP_EndDate.ShowCheckBox = $True
    $DTP_EndDate.Checked = $false

    $DTP_EndDate.Add_ValueChanged({
        if ($DTP_FromDate.Checked -and $DTP_EndDate.Checked)
        {
            sort-sessionLog
        }
    })

    $GB_Logs.Controls.Add($DTP_EndDate)

    $BTN_ResetSearch.Text = "Reset"
    $system_drawing_point.X = 773
    $system_drawing_point.Y = 23
    $BTN_ResetSearch.Location = $system_drawing_point
    $system_drawing_size.Height = 20
    $system_drawing_size.Width = 75
    $BTN_ResetSearch.Size = $system_drawing_size

    $BTN_ResetSearch.Add_Click({
        $DTP_FromDate.Checked = $false
        $DTP_EndDate.Checked = $false
        $TB_UserSort.Text = "User Filter"
        sort-sessionLog
    })

    $GB_Logs.Controls.Add($BTN_ResetSearch)

    $system_drawing_point.X = 6
    $system_drawing_point.Y = 51
    $DGV_Sessions.Location = $system_drawing_point
    $system_drawing_size.Height = 219
    $system_drawing_size.Width = 848
    $DGV_Sessions.Size = $system_drawing_size
    $DGV_Sessions.AllowUserToAddRows = $false
    $DGV_Sessions.AllowUserToDeleteRows = $false
    $DGV_Sessions.AutoSizeColumnsMode = "Fill"
    $DGV_Sessions.ColumnCount = 3
    $DGV_Sessions.Columns[0].Name = "User"
    $DGV_Sessions.Columns[1].Name = "Date"
    $DGV_Sessions.Columns[2].Name = "SessionID"
    $DGV_Sessions.SelectionMode = "FullRowSelect"
    $DGV_Sessions.RowHeadersVisible = $false

    $DGV_Sessions.Add_SelectionChanged({
        select-Session
    })
    
    $GB_Logs.Controls.Add($DGV_Sessions)

    $GB_Actions.Text = "Actions"
    $system_drawing_point.X = 10
    $system_drawing_point.Y = 276
    $GB_Actions.Location = $system_drawing_point
    $system_drawing_size.Height = 326
    $system_drawing_size.Width = 419
    $GB_Actions.Size = $system_drawing_size

    $GB_Logs.Controls.Add($GB_Actions)

    $system_drawing_point.X = 6
    $system_drawing_point.Y = 19
    $DGV_Actions.Location = $system_drawing_point
    $system_drawing_size.Height = 301
    $system_drawing_size.Width = 400
    $DGV_Actions.Size = $system_drawing_size
    $DGV_Actions.ColumnCount = 3
    $DGV_Actions.Columns[0].Name = "Action"
    $DGV_Actions.Columns[1].Name = "Changed Value"
    $DGV_Actions.Columns[2].Name = "New Value"
    $DGV_Actions.AutoSizeColumnsMode = "Fill"
    $DGV_Actions.AllowUserToAddRows = $false
    $DGV_Actions.AllowUserToDeleteRows = $false
    $DGV_Actions.RowHeadersVisible = $false
    $DGV_Actions.SelectionMode = "FullRowSelect"
    $DGV_Actions.Add_SelectionChanged({
        
        Select-Action $DGV_Actions.CurrentRow.Index
    })

    $GB_Actions.Controls.Add($DGV_Actions)

    $GB_ActionDetails.Text = "Action Details"
    $system_drawing_point.X = 435
    $system_drawing_point.Y = 276
    $GB_ActionDetails.Location = $system_drawing_point
    $system_drawing_size.Height = 326
    $system_drawing_size.Width = 419
    $GB_ActionDetails.Size = $system_drawing_size

    $GB_Logs.Controls.Add($GB_ActionDetails)

    $system_drawing_point.X = 6
    $system_drawing_point.Y = 19
    $DGV_ActionDetails.Location = $system_drawing_point
    $system_drawing_size.Height = 301
    $system_drawing_size.Width = 400
    $DGV_ActionDetails.Size = $system_drawing_size
    $DGV_ActionDetails.ColumnCount = 3
    $DGV_ActionDetails.Columns[0].Name = "Action Name"
    $DGV_ActionDetails.Columns[1].Name = "Explanation"
    $DGV_ActionDetails.Columns[2].Name = "Error Code (If any)"
    $DGV_ActionDetails.AutoSizeColumnsMode = "Fill"
    $DGV_ActionDetails.SelectionMode = "FullRowSelect"
    $DGV_ActionDetails.AllowUserToAddRows = $false
    $DGV_ActionDetails.AllowUserToDeleteRows = $false
    $DGV_ActionDetails.RowHeadersVisible = $false

    $GB_ActionDetails.Controls.Add($DGV_ActionDetails)

    #region functions
    function Load_Admins()
    {
        $admins = Get-ADGroupMember "$($env:AdminGroup)"
        foreach ($admin in $admins)
        {
            $user = Get-ADUser ($admin.SamAccountName)
            $DGV_Admins.Rows.Add("$($admin.SamAccountName)","$($admin.name)","$($user.UserPrincipalName)")
        }
    }
    function Load_Logs()
    {
        [xml] $logs = Get-Content $env:sessionLogLocation
        $sessions = $logs.SelectNodes("//Session")
        foreach ($session in $sessions)
        {
            $DGV_Sessions.Rows.Add("$($session.User)","$($session.Date)", "$($session.SessionID)")
        }
    }
    function select-Session()
    {
        #Get the Logs
        [xml] $logs = Get-Content $env:sessionLogLocation
        $selectedSessionId = $DGV_Sessions.SelectedRows.Cells[2].Value
        $sessionNode = $logs.SelectSingleNode("/Sessions/Session[@SessionID='$selectedSessionId']")
        #Clears the Actions Data GridView
        $DGV_Actions.Rows.Clear()
        
        #If the Session had any actions then add them to the Actions DataGridView
        if ($sessionNode.ChildNodes.Count -gt 0)
        {
            for ($i = 0; $i -lt $sessionNode.ChildNodes.Count; $i++)
            {
                $DGV_Actions.Rows.Add("$($sessionNode.ChildNodes[$i].ActionType)", "$($sessionNode.ChildNodes[$i].OldValue)", "$($sessionNode.ChildNodes[$i].NewValue)")
            }
        }
    }
    function sort-sessionLog ()
    {
        #clears the $sessionLog if it contains any elements
        [xml] $logs = Get-Content $env:sessionLogLocation
        if (!($TB_UserSort.Text -eq "User Filter"))
        {
            if ($DGV_Sessions.RowCount -gt 0)
            {
                $DGV_Sessions.Rows.Clear()
                $DGV_Actions.Rows.Clear()
                $DGV_ActionDetails.Rows.Clear()
            }
            $sortedSessions = $logs.SelectNodes("/Sessions/Session[@User='$($TB_UserSort.Text)']")
            foreach($sortedSession in $sortedSessions)
            {
                if ($DTP_FromDate.Checked -and $DTP_EndDate.Checked)
                {
                    [DateTime] $sessionDate = $sortedSession.Date

                    if (($sessionDate -gt $DTP_FromDate.Value) -and $sessionDate -lt $DTP_EndDate.Value)
                    {
                        $DGV_Sessions.Rows.Add("$($sortedSession.User)", "$($sortedSession.Date)", "$($sortedSession.SessionID)")
                    }
                }
                else
                {
                    $DGV_Sessions.Rows.Add("$($sortedSession.User)", "$($sortedSession.Date)", "$($sortedSession.SessionID)")
                }
            }
        } 
        else {
            if ($DTP_FromDate.Checked -and $DTP_EndDate.Checked)
            {
                if ($DGV_Sessions.RowCount -gt 0)
                {
                    $DGV_Sessions.Rows.Clear()
                    $DGV_Actions.Rows.Clear()
                    $DGV_ActionDetails.Rows.Clear()
                }
                $sessions = $logs.SelectNodes("/Sessions/Session")
                foreach ($session in $sessions)
                {
                    [DateTime] $sessionDate = $session.Date

                    if (($sessionDate -gt $DTP_FromDate.Value) -and ($sessionDate -lt $DTP_EndDate.Value))
                    {
                        $DGV_Sessions.Rows.Add("$($session.User)", "$($session.Date)", "$($session.SessionID)")
                    }
                }
            }
            else
            {
                if ($DGV_Sessions.RowCount -gt 0)
                {
                    $DGV_Sessions.Rows.Clear()
                    $DGV_Actions.Rows.Clear()
                    $DGV_ActionDetails.Rows.Clear()
                }
                $sessions = $logs.SelectNodes("/Sessions/Session")
                foreach ($session in $sessions)
                {
                    $DGV_Sessions.Rows.Add("$($session.User)", "$($session.Date)", "$($session.SessionID)")
                }
            }
        }

    }
    function Select-Action($index)
    {
        [xml] $logs = Get-Content $env:sessionLogLocation
        $selectedSessionId = $DGV_Sessions.SelectedRows.Cells[2].Value
        $sessionNode = $logs.SelectSingleNode("/Sessions/Session[@SessionID='$selectedSessionId']")
        #clears the Action Details DataGridView
        $DGV_ActionDetails.Rows.Clear()

        for ($i = 0; $i -lt $sessionNode.ChildNodes.Count; $i++)
        {
            if (($sessionNode.ChildNodes[$i].ChildNodes.Count -gt 0) -and ($i -eq $index))
            {
                $actionDetails = $sessionNode.ChildNodes[$i].ChildNodes
                for ($b = 0; $b -lt $actionDetails.Count; $b++)
                {
                    $DGV_ActionDetails.Rows.Add("$($actionDetails[$b].Detail)", "$($actionDetails[$b].Information)", "$($actionDetails[$b].ErrorCode)")
                }
            }
        }

        
    }
    function Modify-Users($method, $user, $group)
    {
        if ($method -eq "Add")
        {
            $addUserAction = add-ActionElementToSessionLog -action "Adding User to $group"

            $addUserMessage = [System.Windows.MessageBox]::Show("Are you adding more than one user?", "Add Users", [System.Windows.MessageBoxButton]::YesNo, [System.Windows.MessageBoxImage]::Question, [System.Windows.MessageBoxResult]::Yes)

            if ($addUserMessage -eq "Yes")
            {
                $file = get-File
                if ($file)
                {
                    $fileExt = $file.split(".")[1]

                    if ($fileExt -eq "csv")
                    {
                        $csv = Import-Csv $file -Header "User"
                        $i = 1
                        $nodeCount = $csv.Count
                        foreach ($line in $csv)
                        {
                            $percent = ($i / $nodeCount) * 100
                            Write-Progress -Activity "Adding Group Members" -Status "$percent% Complete:" -PercentComplete $percent
                            try {
                                Add-ADGroupMember -Identity "$($group)" -Members ($line.User)
                            } catch {
                                add-actionDetails -detailTitle "Error Adding User" -detailExplanation "$($_). Specified Account: $($line.User)" -actionElement $addUserAction
                            } finally {
                                $user = Get-ADUser ($line.User)
                                if ((Get-ADGroupMember -Identity $group) -contains $user)
                                {
                                    if ($group -eq "$($env:AdminGroup)")
                                    {
                                     
                                        $DGV_Admins.Rows.Add("$($user.SamAccountName)", "$($user.Name)", "$($user.UserPrincipalName)")
                                    } else
                                    {
                                        $DGV_Users.Rows.Add("$($user.SamAccountName)", "$($user.Name)", "$($user.UserPrincipalName)")
                                    }
                                    add-actionDetails -detailTitle "Member Added" -detailExplanation "Added ($($line.User) as Member" -actionElement $addUserAction 
                                }
                            }
                            $i++
                        }
                    } elseif ($fileExt -eq "xml")
                    {
                        Write-Host "Loading XML"
                        [xml] $userFile = Get-Content $file

                        $nodes = $userFile.SelectNodes("//Members//Member")
                        
                        $i = 1
                        $nodeCount = $nodes.Count
                        foreach ($line in $nodes)
                        {
                            $percent = $i / $nodeCount
                            Write-Progress -Activity "Adding Group Members" -Status "$percent% Complete:" -PercentComplete $percent
                            try {
                                Add-ADGroupMember -Identity "$($group)" -Members "$($line.FourbyFour)"
                            } catch {
                                add-actionDetails -detailTitle "Error Adding User" -detailExplanation "$($_). Specified Account: $($line.User)" -actionElement $addUserAction
                            } finally {
                                $user = Get-ADUser ($line.FourbyFour)
                                if ((Get-ADGroupMember -Identity $group) -contains $user)
                                {
                                    if ($group -eq "$($env:AdminGroup)")
                                    {
                                     
                                        $DGV_Admins.Rows.Add("$($user.SamAccountName)", "$($user.Name)", "$($user.UserPrincipalName)")
                                    } else
                                    {
                                        $DGV_Users.Rows.Add("$($user.SamAccountName)", "$($user.Name)", "$($user.UserPrincipalName)")
                                    }
                                    add-actionDetails -detailTitle "Member Added" -detailExplanation "Added ($($line.User) as Member" -actionElement $addUserAction 
                                }
                            }        
                            $i++
                        }

                    }
                }
                save-actionElementToSessionLog -element $addUserAction
                save-sessionLog -log $sessionLog -element $sessionElement
            } 
            else
            {

                $Add_SingleUserForm = New-Object System.Windows.Forms.Form
                $TB_UserToAdd = New-Object System.Windows.Forms.TextBox
                $BTN_AddUser = New-Object System.Windows.Forms.Button
                
                $system_drawing_size.Height = 131
                $system_drawing_size.Width = 224
                $Add_SingleUserForm.Size = $system_drawing_size
                $Add_SingleUserForm.StartPosition = "CenterParent"
                $Add_SingleUserForm.Text = "Add Single User"
                $Add_SingleUserForm.TopMost = $True

                $system_drawing_point.X = 23
                $system_drawing_point.Y = 12
                $TB_UserToAdd.Location = $system_drawing_point
                $system_drawing_size.Height = 20
                $system_drawing_size.Width = 150
                $TB_UserToAdd.Size = $system_drawing_size
                $TB_UserToAdd.Text = "Please enter a users 4x4"
                $TB_UserToAdd.Add_Click({
                    $TB_UserToAdd.Text = ""
                })
                $TB_UserToAdd.Add_TextChanged({
                    if ($TB_UserToAdd.Text.Length -eq 8)
                    {
                        $BTN_AddUser.Enabled = $True
                    }
                })
                $TB_UserToAdd.Add_Leave({
                    if ($TB_UserToAdd.Text.Length -eq 0)
                    {
                        $TB_UserToAdd.Text = "Please enter a users 4x4"
                    }
                })
                $Add_SingleUserForm.Controls.Add($TB_UserToAdd)

                $system_drawing_point.X = 55
                $system_drawing_point.Y = 47
                $BTN_AddUser.Location = $system_drawing_point
                $system_drawing_size.Height = 23
                $system_drawing_size.Width = 75
                $BTN_AddUser.Size = $system_drawing_size
                $BTN_AddUser.Text = "Add User"
                $BTN_AddUser.Enabled = $false

                $BTN_AddUser.Add_Click({
                    try {
                        $adUser = Get-ADUser $TB_UserToAdd.Text
                    } catch
                    {
                        [System.Windows.MessageBox]::Show("No User was found for the following 4x4 $($TB_UserToAdd.Text)", "Invalid User", "OK", [System.Windows.MessageBoxImage]::Error)
                        return
                    }
                    try {
                        Add-ADGroupMember $group -Member $adUser
                    } catch
                    {
                        [System.Windows.MessageBox]::Show("Unable to add the User to the group.`n The user could already be a member.", "Error", "OK", "Error")
                        return
                    }
                    if ($group -eq "$($env:AdminGroup)")
                    {
                        $DGV_Admins.Rows.Add("$($adUser.SamAccountName)", "$($adUser.Name)", "$($adUser.UserPrincipalName)")
                    }
                    if ($group -eq "$($env:UsersGroup)")
                    {
                        $DGV_Users.Rows.Add("$($adUser.SamAccountName)", "$($adUser.Name)", "$($adUser.UserPrincipalName)")
                    }
                    add-actionDetails -detailTitle "Added User to $group" -detailExplanation "User added: ($($adUser.SamAccountName))" -actionElement $addUserAction
                    save-actionElementToSessionLog -element $addUserAction
                    save-sessionLog -log $sessionLog -element $sessionElement
                    $Add_SingleUserForm.Close()
                })

                $Add_SingleUserForm.Controls.Add($BTN_AddUser)

                $Add_SingleUserForm.ShowDialog()

            }
        }
        if ($method -eq "Remove")
        {
            $removeUserAction = add-ActionElementToSessionLog -action "Removing User"
            $removeUser = [System.Windows.MessageBox]::Show("You are about to remove: $user from $group. `n Are you sure you want to do this?", "Remove User", [System.Windows.MessageBoxButton]::YesNo, [System.Windows.MessageBoxImage]::Warning, [System.Windows.MessageBoxResult]::No)
            if ($removeUser -eq "Yes")
            {
                Remove-ADGroupMember $group -Members $user -Confirm:$false
                add-actionDetails -detailTitle "Removed User" -detailExplanation "User removed ($user)" -actionElement $removeUserAction
                save-actionElementToSessionLog -element $removeUserAction
                save-sessionLog -log $sessionLog -element $sessionElement
                if ($group -eq "$($env:AdminGroup)")
                {
                    $DGV_Admins.Rows.RemoveAt($DGV_Admins.CurrentRow.Index)
                }
                if ($group -eq "$($env:UsersGroup)")
                {
                    $DGV_Users.Rows.RemoveAt($DGV_Users.CurrentRow.Index)
                }
            }
        }
    }
    
    function Refresh-DataGridViews()
    {
        #todo implement
    }
    #endregion

    $adminPanelForm.Add_Load({
        Load_Admins
        Load_Logs
    })
    $adminPanelForm.ShowDialog() | Out-Null

    #endregion

}

function GenerateInstallForm()
{
    #region Form Objects
    $installForm = New-Object System.Windows.Forms.Form
    $GB_Settings = New-Object System.Windows.Forms.GroupBox
    $TB_Domain = New-Object System.Windows.Forms.TextBox
    $TB_LEA = New-Object System.Windows.Forms.TextBox
    $TB_LL = New-Object System.Windows.Forms.TextBox
    $TB_AADG = New-Object System.Windows.Forms.TextBox
    $TB_UADG = New-Object System.Windows.Forms.TextBox
    $BTN_Domain = New-Object System.Windows.Forms.Button
    $BTN_LEA = New-Object System.Windows.Forms.Button
    $BTN_LL = New-Object System.Windows.Forms.Button
    $BTN_AADG = New-Object System.Windows.Forms.Button
    $BTN_UADG = New-Object System.Windows.Forms.Button
    $LBL_Help = New-Object System.Windows.Forms.Label
    $RTB_HelpDetail = New-Object System.Windows.Forms.RichTextBox
    $GB_AdminGroup = New-Object System.Windows.Forms.GroupBox
    $GB_UserGroup = New-Object System.Windows.Forms.GroupBox
    $DGV_AdminGroup = New-Object System.Windows.Forms.DataGridView
    $DGV_UserGroup = New-Object System.Windows.Forms.DataGridView

    $Admin_contextMenu = New-Object System.Windows.Forms.ContextMenuStrip
    $addAdmin = New-Object System.Windows.Forms.ToolStripMenuItem
    $removeAdmin = New-Object System.Windows.Forms.ToolStripMenuItem

    $User_ContextMenu = New-Object System.Windows.Forms.ContextMenuStrip
    $add_User = New-Object System.Windows.Forms.ToolStripMenuItem
    $remove_User = New-Object System.Windows.Forms.ToolStripMenuItem
    #endregion
    [XML] $settingsXML = Get-Content $SettingsFile
    $node = $settingsXML.SelectSingleNode("//Setting")
    function Load_Install_Admins
    {
        $adminG = Get-ADGroupMember "$($TB_AADG.Text)"
        foreach ($admin in $adminG)
        {
            $user = Get-ADUser ($admin.SamAccountName) -Properties *

            $DGV_AdminGroup.Rows.Add("$($admin.SamAccountName)", "$($user.GivenName) $($user.Surname)", "$($User.UserPrincipalName)")
        }
    }
    function Load_Install_Users
    {
        $groupUser = Get-ADGroupMember "$($TB_UADG.Text)"
        foreach ($user in $groupUser)
        {
            $adUser = Get-ADUser ($user.SamAccountName) -Properties *

            $DGV_UserGroup.Rows.Add("$($user.SamAccountName)", "$($adUser.GivenName) $($adUser.Surname)", "$($adUser.UserPrincipalName)")
        }
    }
    function Install_Modify_Group([System.Windows.Forms.DataGridView] $groupView, $method, $group)
    {
        if ($method -eq "Add")
        {
            $csv = Import-Csv (get-File) -Header "User"  -ErrorAction SilentlyContinue
            if ($csv)
            {
                foreach ($line in $csv)
                {
                    try {
                        Add-ADGroupMember -Identity "$group"  -Members "$($line.User)"
                        $user = Get-ADUser "$($line.User)" -Properties *
                        $groupView.Rows.Add("$($user.SamAccountName)", "$($user.GivenName) $($user.Surname)", "$($user.UserPrincipalName)")
                    } catch [Microsoft.ActiveDirectory.Management.ADException]
                    {

                        [System.Windows.MessageBox]::Show("The User $($line.User) is already in the group", "Error", "OK", "Warning")
                    }

                }
            }
        } else {

            foreach ($selectedRow in $groupView.SelectedRows)
            {    
                Remove-ADGroupMember -Identity $group -Members "$($selectedRow.Cells[0].Value)" -Confirm:$false
                $groupView.Rows.Remove($selectedRow)
            }
        }
    }

    $system_drawing_size = New-Object System.Drawing.Size
    $system_drawing_point = New-Object System.Drawing.Point

    $system_drawing_size.Height = 471
    $system_drawing_size.Width = 754
    $installForm.FormBorderStyle = "FixedSingle"
    $installForm.Size = $system_drawing_size
    $installForm.Icon = "C:\Program Files\Common Files\server_earth_aTu_icon.ico"
    $installForm.ShowIcon = $True
    $installForm.MaximizeBox = $false
    $installForm.Text = "Install SCGUI"
    $installForm.StartPosition = "CenterScreen"

    $GB_Settings.Text = "Settings"
    $system_drawing_size.Height = 157
    $system_drawing_size.Width = 714
    $GB_Settings.Size = $system_drawing_size
    $system_drawing_point.X = 12
    $system_drawing_point.Y = 12
    $GB_Settings.Location = $system_drawing_point
    
    $installForm.Controls.Add($GB_Settings)

    $TB_Domain.Text = "Domain"
    $system_drawing_size.Height = 20
    $system_drawing_size.Width = 183
    $TB_Domain.Size = $system_drawing_size
    $system_drawing_point.X = 6
    $system_drawing_point.Y = 19
    $TB_Domain.Location = $system_drawing_point

    $TB_Domain.Add_Click({
        if ($TB_Domain.Text -eq "Domain")
        {
            $TB_Domain.text = ""
        }
    })
    $TB_Domain.Add_Leave({
        if ($TB_Domain.Text.Length -eq 0)
        {
            $TB_Domain.Text = "Domain"
        } else
        {
            if ($TB_Domain.Text -ne "Domain")
            {
                $node.Domain = "$($TB_Domain.Text)"
                $settingsXML.Save($SettingsFile)
            }
        }
    })

    $GB_Settings.Controls.Add($TB_Domain)

    $TB_LEA.Size = $system_drawing_size
    $TB_LEA.Text = "Local Exchange Address"
    $system_drawing_point.Y = 45
    $TB_LEA.Location = $system_drawing_point

    $TB_LEA.Add_Click({
        if ($TB_LEA.Text -eq "Local Exchange Address")
        {
            $TB_LEA.Text = ""
        }
    })

    $TB_LEA.Add_Leave({
        if ($TB_LEA.TextLength -eq 0)
        {
            $TB_LEA.Text = "Local Exchange Address"
        }
        else
        {
            if ($TB_LEA.Text -ne "Local Exchange Address")
            {
                $node.LocalExchangeAddress = "$($TB_LEA.Text)"
                $settingsXML.Save($SettingsFile)
            }
        }
    })

    $GB_Settings.Controls.Add($TB_LEA)

    $TB_LL.Text = "Log Location"
    $TB_LL.Size = $system_drawing_size
    $system_drawing_point.Y = 71
    $TB_LL.Location = $system_drawing_point

    $TB_LL.Add_Click({
        $saveLocation = New-Object System.Windows.Forms.SaveFileDialog
        $saveLocation.DefaultExt = "xml"
        $saveLocation.InitialDirectory = "C:\ProgramData\SCGUI"
        $saveLocation.Filter = "XML (*.xml)|*.xml"
        $saveLocation.Add_FileOk({
            if ($TB_LL.TextLength -gt 0)
            {
                $TB_LL.Text = ""
            }
            $TB_LL.Text = "$($saveLocation.FileName)"
            $node.LogLocation = "$($TB_LL.Text)"
            $settingsXML.Save($SettingsFile)
        })
        $saveLocation.ShowDialog()
    })

    $GB_Settings.Controls.Add($TB_LL)

    $TB_AADG.Text = "Admin AD Group"
    $TB_AADG.Size = $system_drawing_size
    $system_drawing_point.Y = 97
    $TB_AADG.Location = $system_drawing_point

    $TB_AADG.Add_Click({
        if ($TB_AADG.Text -eq "Admin AD Group")
        {
            $TB_AADG.Text = ""
        }
    })
    $TB_AADG.Add_Leave({
        if ($TB_AADG.Text -eq "Admin AD Group")
        {
            $GB_AdminGroup.Visible = $false
            $DGV_AdminGroup.Rows.Clear()
            return
        }
        if ($TB_AADG.TextLength -gt 0)
        {
            if (($TB_AADG.Text.Substring(0,1) -match "^[a-zA-Z0-9]") -and ($TB_AADG.Text.Substring(($TB_AADG.Text.Length - 1),1) -match "^[a-zA-Z0-9]"))
            {
                $UADG = Get-ADGroup -Identity "$($TB_AADG.Text)" -ErrorAction SilentlyContinue
                #checks if ADGroup Exists
                if ($UADG)
                {
                    $continueAlert = [System.Windows.MessageBox]::Show("The Group already exists.`n Would you like to use this group: $($TB_AADG.Text)?", "Group Exists", [System.Windows.MessageBoxButton]::YesNo, [System.Windows.MessageBoxImage]::Question, [System.Windows.MessageBoxResult]::No)
                    if ($continueAlert -eq "Yes")
                    {
                        $GB_AdminGroup.Visible = $True
                        $TB_AADG.Text = "$($TB_AADG.Text)"
                        $node.AdminGroup = "$($TB_AADG.Text)"
                        $settingsXML.Save($SettingsFile)
                        Load_Install_Admins
                    }
                    else {
                        $TB_AADG.Text = ""
                    }
                } 
                else
                {
                    $createAlert = [System.Windows.MessageBox]::Show("The specified Group does not exist.`n Would you like to create this group: $($TB_UADG.Text)?", "Group does not Exist", [System.Windows.MessageBoxButton]::YesNo, [System.Windows.MessageBoxImage]::Question, [System.Windows.MessageBoxResult]::No)
                    if ($createAlert -eq "Yes")
                    {
                        New-ADGroup ($TB_AADG.Text) -DisplayName ($TB_AADG.Text) -GroupCategory Security -Path "ou=SCGUI,ou=DLs,OU=Exchange,dc=sooner,dc=net,dc=ou,dc=edu" -GroupScope Universal
                        $GB_AdminGroup.Visible = $True
                        $node.AdminGroup = "$($TB_AADG.Text)"
                        $settingsXML.Save($SettingsFile)
                        Load_Install_Admins
                    }
                    else
                    {
                        $TB_AADG.Text = ""
                    }
                }
            } else
            {
                #Validation
                if (!($TB_AADG.Text.Substring(0,1) -match "^[a-zA-Z0-9]"))
                {
                    $TB_AADG.Text = ($TB_AADG.Text).Remove(0,1)
                }
                if (!($TB_AADG.Text.Substring(($TB_AADG.TextLength - 1),1) -match "^[a-zA-Z0-9]"))
                {
                    $TB_AADG.Text = ($TB_AADG.Text).Remove(($TB_AADG.TextLength -1), 1)
                }
            }
        }
        if ($TB_AADG.TextLength -eq 0)
        {
            $GB_AdminGroup.Visible = $false
            $DGV_AdminGroup.Rows.Clear()
            $TB_AADG.Text = "Admin AD Group"
        }
    })

    $GB_Settings.Controls.Add($TB_AADG)

    $TB_UADG.Text = "User AD Group"
    $TB_UADG.Size = $system_drawing_size
    $system_drawing_point.Y = 123
    $TB_UADG.Location = $system_drawing_point

    $TB_UADG.Add_Click({
        if ($TB_UADG.Text -eq "User AD Group")
        {
            $TB_UADG.Text = ""
        }
    })
    $TB_UADG.Add_Leave({
        if ($TB_UADG.Text -eq "User AD Group")
        {
            $GB_UserGroup.Visible = $false
            $DGV_UserGroup.Rows.Clear()
            return
        }
        if ($TB_UADG.TextLength -gt 0)
        {
            if (($TB_UADG.Text.Substring(0,1) -match "^[a-zA-Z0-9]") -and ($TB_UADG.Text.Substring(($TB_UADG.Text.Length - 1),1) -match "^[a-zA-Z0-9]"))
            {
                $UADG = Get-ADGroup -Identity "$($TB_UADG.Text)" -ErrorAction SilentlyContinue
                #Checks if Group Already Exists
                if ($UADG)
                {
                    $continueAlert = [System.Windows.MessageBox]::Show("The Group already exists.`n Would you like to use this group: $($TB_UADG.Text)?", "Group Exists", [System.Windows.MessageBoxButton]::YesNo, [System.Windows.MessageBoxImage]::Question, [System.Windows.MessageBoxResult]::No)
                    if ($continueAlert -eq "Yes")
                    {
                        $TB_UADG.Text = "$($TB_UADG.Text)"
                        $GB_UserGroup.Visible = $True
                        $node.UsersGroup = "$($TB_UADG.Text)"
                        $settingsXML.Save($SettingsFile)
                        Load_Install_Users
                    } else {$TB_UADG.Text = ""}
                } 
                else
                {
                    $createAlert = [System.Windows.MessageBox]::Show("The specified Group does not exist.`n Would you like to create this group: $($TB_UADG.Text)?", "Group does not Exist", [System.Windows.MessageBoxButton]::YesNo, [System.Windows.MessageBoxImage]::Question, [System.Windows.MessageBoxResult]::No)
                    if ($createAlert -eq "Yes")
                    {
                        New-ADGroup ($TB_AADG.Text) -DisplayName ($TB_AADG.Text) -GroupCategory Security -Path "ou=SCGUI,ou=DLs,OU=Exchange,dc=sooner,dc=net,dc=ou,dc=edu" -GroupScope Universal
                        $GB_UserGroup.Visible = $True
                        $node.UsersGroup = "$($TB_UADG.Text)"
                        $settingsXML.Save($SettingsFile)
                        Load_Install_Users
                    } else{$TB_UADG.Text = ""}
                }
            } else
            {
                #Validation
                if (!($TB_UADG.Text.Substring(0,1) -match "^[a-zA-Z0-9]"))
                {
                    $TB_UADG.Text = ($TB_UADG.Text).Remove(0,1)
                }
                if (!($TB_UADG.Text.Substring(($TB_UADG.TextLength - 1),1) -match "^[a-zA-Z0-9]"))
                {

                    $TB_UADG.Text = ($TB_UADG.Text).Remove(($TB_UADG.TextLength -1), 1)
                }
            }
        }
        if ($TB_UADG.TextLength -eq 0)
        {
            $GB_UserGroup.Visible = $false
            $DGV_UserGroup.Rows.Clear()
            $TB_UADG.Text = "User AD Group"
        }
    })
    $GB_Settings.Controls.Add($TB_UADG)

    $bitMap = New-Object System.Drawing.BitMap -ArgumentList "C:\Users\it_zdivine\SCGUI\help.png", $True
    $BTN_Domain.Text = ""
    $BTN_Domain.BackgroundImage = $bitMap
    $system_drawing_point.X = 195
    $system_drawing_point.Y = 19
    $BTN_Domain.Location = $system_drawing_point
    $system_drawing_size.Height = 21
    $system_drawing_size.Width = 21
    $BTN_Domain.Size = $system_drawing_size
    $BTN_Domain.BackgroundImageLayout = "Center"

    $BTN_Domain.Add_MouseHover({
        $LBL_Help.Text = "Domain Help"

        $RTB_HelpDetail.Text = "The specified network to use as the default domain. IE SOONER\it_example.`nThe Domain is used to specify which users have access to the program based upon access to either the Admin and Users Group"
    })
    $GB_Settings.Controls.Add($BTN_Domain)

    $BTN_LEA.Text = ""
    $BTN_LEA.BackgroundImage = $bitMap
    $BTN_LEA.BackgroundImageLayout = "Center"
    $BTN_LEA.Size = $system_drawing_size
    $system_drawing_point.Y = 45
    $BTN_LEA.Location = $system_drawing_point

    $BTN_LEA.Add_MouseHover({
        $LBL_Help.Text = "Local Exchange Help"

        $RTB_HelpDetail.Text = "This setting needs to be set for access to local exchange.`nPlease input an address to one of your servers that has Exchange install on it. Ex: it-ponyexpress.sooner.net.ou.edu"
    })
    $GB_Settings.Controls.Add($BTN_LEA)

    $BTN_LL.Text = ""
    $BTN_LL.BackgroundImage = $bitMap
    $BTN_LL.BackgroundImageLayout = "Center"
    $BTN_LL.Size = $system_drawing_size
    $system_drawing_point.Y = 71
    $BTN_LL.Location = $system_drawing_point

    $BTN_LL.Add_MouseHover({
        $LBL_Help.Text = "Log Location Help"

        $RTB_HelpDetail.Text = "This setting provides you with the option to set the log location to any folder you choose. Or you can leave the default location.`nThe logs provide you with easy access to view all changes made by any of the users or admins."
    })

    $GB_Settings.Controls.Add($BTN_LL)

    $BTN_AADG.Text = ""
    $BTN_AADG.BackgroundImage = $bitMap
    $BTN_AADG.BackgroundImageLayout = "Center"
    $BTN_AADG.Size = $system_drawing_size
    $system_drawing_point.Y = 96
    $BTN_AADG.Location = $system_drawing_point

    $BTN_AADG.Add_MouseHover({
        $LBL_Help.Text = "Admin Group"

        $RTB_HelpDetail.Text = "This specifies the group who will manage and over see the program. `nThey will have access to the Admin Panel and will be able to add users to both the Admin Group And the Users Group."
    })
    $GB_Settings.Controls.Add($BTN_AADG)

    $BTN_UADG.Text = ""
    $BTN_UADG.BackgroundImage = $bitMap
    $BTN_UADG.BackgroundImageLayout = "Center"
    $BTN_UADG.Size = $system_drawing_size
    $system_drawing_point.Y = 122
    $BTN_UADG.Location = $system_drawing_point

    $BTN_UADG.Add_MouseHover({
        $LBL_Help.Text = "Users Group"

        $RTB_HelpDetail.Text = "This group will have access to use the program and nothing else.`n`n*You will have to verify that the user has the neccsary permissions on each one of your server and on office 365 for some functions to work."
    })

    $GB_Settings.Controls.Add($BTN_UADG)

    $LBL_Help.Text = ""
    $system_drawing_point.X = 419
    $system_drawing_point.Y = 19
    $LBL_Help.Location = $system_drawing_point
    $LBL_Help.AutoSize = $True
    $LBL_Help.Font = "Microsoft Sans Serif, 14.25pt, style=Bold"

    $GB_Settings.Controls.Add($LBL_Help)

    $RTB_HelpDetail.Text = ""
    $system_drawing_point.X = 251
    $system_drawing_point.Y = 47
    $RTB_HelpDetail.Location = $system_drawing_point
    $system_drawing_size.Height = 96
    $system_drawing_size.Width = 447
    $RTB_HelpDetail.Size = $system_drawing_size
    $RTB_HelpDetail.ScrollBars = "Vertical"
    $RTB_HelpDetail.ReadOnly = $True

    $GB_Settings.Controls.Add($RTB_HelpDetail)

    $GB_AdminGroup.Text = "Admin Group Members"
    $system_drawing_point.X = 18
    $system_drawing_point.Y = 175
    $GB_AdminGroup.Location = $system_drawing_point
    $system_drawing_size.Height = 245
    $system_drawing_size.Width = 330
    $GB_AdminGroup.Size = $system_drawing_size
    $GB_AdminGroup.Visible = $false

    $installForm.Controls.Add($GB_AdminGroup)

    $GB_UserGroup.Text = "User Group Members"
    $system_drawing_point.X = 380
    $GB_UserGroup.Location = $system_drawing_point
    $GB_UserGroup.Size = $system_drawing_size
    $GB_UserGroup.Visible = $false

    $installForm.Controls.Add($GB_UserGroup)

    $DGV_AdminGroup.AutoSizeColumnsMode = "Fill"
    $DGV_AdminGroup.AllowUserToAddRows = $false
    $DGV_AdminGroup.AllowUserToDeleteRows = $false
    $DGV_AdminGroup.AllowUserToOrderColumns = $false
    $DGV_AdminGroup.ColumnCount = 3
    $DGV_AdminGroup.Columns[0].Name = "4x4"
    $DGV_AdminGroup.Columns[1].Name = "Name"
    $DGV_AdminGroup.Columns[2].Name = "UPN"
    $DGV_AdminGroup.SelectionMode = "FullRowSelect"

    $addAdmin.Text = "Add Admins"
    $addAdmin.Add_Click({
        Install_Modify_Group -groupView $DGV_AdminGroup -method "Add" -group "$($TB_AADG.Text)"
    })

    $Admin_contextMenu.Items.Add($addAdmin)

    $removeAdmin.Text = "Remove Admins"
    $removeAdmin.Add_Click({
        Install_Modify_Group -groupView $DGV_AdminGroup -method "Remove" -group "$($TB_AADG.Text)"
    })

    $Admin_contextMenu.Items.Add($removeAdmin)

    $DGV_AdminGroup.ContextMenuStrip = $Admin_contextMenu

    $system_drawing_size.Height = 220
    $system_drawing_size.Width = 318
    $DGV_AdminGroup.Size = $system_drawing_size
    $system_drawing_point.X = 6
    $system_drawing_point.Y = 19
    $DGV_AdminGroup.Location = $system_drawing_point

    $GB_AdminGroup.Controls.Add($DGV_AdminGroup)

    $DGV_UserGroup.AutoSizeColumnsMode = "Fill"
    $DGV_UserGroup.AllowUserToAddRows = $false
    $DGV_UserGroup.AllowUserToDeleteRows = $false
    $DGV_UserGroup.AllowUserToOrderColumns = $false
    $DGV_UserGroup.ColumnCount = 3
    $DGV_UserGroup.Columns[0].Name = "4x4"
    $DGV_UserGroup.Columns[1].Name = "Name"
    $DGV_UserGroup.Columns[2].Name = "UPN"
    $DGV_UserGroup.SelectionMode = "FullRowSelect"

    $system_drawing_size.Height = 220
    $system_drawing_size.Width = 318
    $DGV_UserGroup.Size = $system_drawing_size
    $system_drawing_point.X = 6
    $system_drawing_point.Y = 19
    $DGV_UserGroup.Location = $system_drawing_point

    $add_User.Text = "Add Users"
    $add_User.Add_Click({
        Install_Modify_Group -groupView $DGV_UserGroup -method "Add" -group "$($TB_UADG.Text)"
    })
    $User_ContextMenu.Items.Add($add_User)

    $remove_User.Text = "Remove Users"
    $remove_User.Add_Click({
        Install_Modify_Group -groupView $DGV_UserGroup -method "Remove" -group "$($TB_UADG.Text)"
    })

    $User_ContextMenu.Items.Add($remove_User)
    $DGV_UserGroup.ContextMenuStrip = $User_ContextMenu
    
    $GB_UserGroup.Controls.Add($DGV_UserGroup)
    
    $installForm.Add_Closing({
        Load_Settings
        [System.XML.XMLDocument] $sessionLog = New-Object System.XML.XMLDocument
        [System.XML.XMLElement] $sessions = $sessionLog.CreateElement("Sessions")
        $sessionLog.AppendChild($sessions)
        save-sessionLog($sessionLog)
        $acl = Get-Acl C:\ProgramData\SCGUI

        $AR = New-Object System.Security.AccessControl.FileSystemAccessRule("Users", "Read,Write", "ContainerInherit,ObjectInherit", "None", "Allow")

        $acl.SetAccessRule($AR)
        
        $AR2 = New-Object System.Security.AccessControl.FileSystemAccessRule("Administrators", "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")
        $acl.SetAccessRule($AR2)
        $AR3 = New-Object System.Security.AccessControl.FileSystemAccessRule("System", "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")
        $acl.SetAccessRule($AR3)
        $AR4 = New-Object System.Security.AccessControl.FileSystemAccessRule("$($env:Domain)\$($env:AdminGroup)", "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")
        $acl.SetAccessRule($AR4)
        $AR5 = New-Object System.Security.AccessControl.FileSystemAccessRule("$($env:Domain)\$($env:UsersGroup)", "Read,Write", "ContainerInherit,ObjectInherit", "None", "Allow")
        $acl.SetAccessRule($AR5)

        Set-Acl C:\ProgramData\SCGUI -AclObject $acl
    })
    $installForm.Add_Shown({
        [System.Windows.MessageBox]::Show("This Form saves every change once the control has left the object. IE: Clicking on another Textbox or clicking on the form. Hover over the Question marks to reveal the help message", "Info", "OK", "Info")
    })

    $installForm.ShowDialog()
}
#validates the user is in one of the two ad Groups
function validateUser()
{
    $validateUserAction = add-ActionElementToSessionLog -action "Validating User" 
    $users = Get-ADGroupMember "$($env:UsersGroup)"
    $admins = Get-ADGroupMember "$($env:AdminGroup)"
    $userNotValidated = $True
    $LocalUser = Get-ADUser $env:USERNAME
    foreach ($user in $users)
    {
        if ($user.distinguishedName -eq "$($LocalUser.DistinguishedName)")
        {
            add-actionDetails -detailTitle "User Validation" -detailExplanation "User is Registered as a valid User" -actionElement $validateUserAction
            $userNotValidated = $false
        }
    }
    foreach ($admin in $admins)
    {
        if ($admin.distinguishedName -eq "$($LocalUser.DIstringuishedName)")
        {
            add-actionDetails -detailTitle "User Validation" -detailExplanation "User is Registered as a valid admin user" -actionElement $validateUserAction
            $userNotValidated = $false
        }
    }
    if ($userNotValidated)
    {
        add-actionDetails -detailTitle "User Validation" -detailExplanation "User ($($env:USERNAME)) is not allowed to use the program." -actionElement $validateUserAction
        save-actionElementToSessionLog -element $validateUserAction
        save-sessionLog -log $sessionLog -element $sessionElement
        [System.Windows.MessageBox]::Show("User is not authorized to use this program.", "User Validation Error", "OK", "Error")
        exit
    }
    save-actionElementToSessionLog -element $validateUserAction
    save-sessionLog -log $sessionLog -element $sessionElement
}

function Check_Update()
{
    #TODO check online for new update

    $value = Get-ItemProperty -Path "$($key)\SCGUI"
    if ([double] $env:Version -gt [double] ($value.Version))
    {
        Set-ItemProperty -Path "$($key)\SCGUI" -Name "Version" -Value $env:Version
    }
}



#region Program Start
Remove-Job * -Force
Check_Update
install-SCGUI
Load_Settings
[xml] $sessionLog = Get-Content $env:sessionLogLocation
$sessionElement = create-SessionLog -sessionLog $sessionLog
validateUser 
GenerateLoginPage 

$notifyIcon.Visible = $false

Get-PSSession | Remove-PSSession

save-sessionLog -log $sessionLog -element $sessionElement
Get-Job | Out-String | Out-Host
exit
#endregion