locked
Keep FileUpload control with its attached files after any buttons postbacks RRS feed

  • Question

  • User-786564416 posted

    I have a FileUpload control "AttachmentsSelecter" . The problem I have is that whenever I clicked any button that make postback, it loses the attached file. I used the <UpdatePanel> and <ContentTemplate>, and <PostBackTrigger> but it still loses the attachment.

    I have a button:

    <asp:Button ID="OpenIncomingInfoWindow" runat="server" BackColor="#6262FF" style="font-size: 30px; text-align: center; font-family: sc_AMEEN;" Height="35px" ForeColor="White" CausesValidation="False" Width="35px" UseSubmitBehavior="False"
                            onMouseOver="this.className='ButtonhoverA'" onMouseOut="this.className='ButtonoutA'" Text="..." />

    What should I do to prevent losing the attachment when clicking "OpenIncomingInfoWindow" button?

    My full aspx code:

    <%@ Page Title="" Language="VB" MasterPageFile="~/MasterPages/MyMasterPage.master" AutoEventWireup="false" CodeFile="NewLetterPosting.aspx.vb" Inherits="NewPosting_NewLetterPosting" %>
    <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
    
    <asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
        <style type="text/css">
                           
                             
             .MainFieldsDivStyle
            {
                border-color: Black;
                width: 70%;
                border-style: solid;
                margin-top: 22px;
                background-color:#C9DCF2;
                opacity:0.8;
                -moz-border-radius: 15px;
                -webkit-border-radius: 15px;
                border-radius: 15px; 
            }     
            
           
                     
                   
            .ErrorMessage
            {
                color: red;
                text-align: right;
                font-style: normal;
                font-size: 28px;
            }
           
            .FooterErrorMessage
            {
                color: red;
                text-align: right;
                font-family: sc_AMEEN;
                font-style: normal;
                font-size: 28px;
                margin-left: 2px;
                margin-right:40px; 
            }
    
            .FileUploadStyle
            {
                direction:rtl;
                -moz-border-radius: 15px;
                -webkit-border-radius: 15px;
                border-radius: 15px; 
            }  
           
            .LabelingCell {
                border: 1px solid Black;
                background-color:#96C2F2;
                width: 170px;
            }
    
            
    
            .ReserverIcon
            {
                margin-right:5px; 
            }
     
            
            .ButtonoutA
            {
                cursor:default;
                text-align:center;  
            } 
              
             .ButtonhoverA
            {
                cursor:pointer;
                text-align:center;  
            } 
    
                    
    
            .Buttonout
            {
                cursor:default;
                -moz-border-radius: 15px;
                -webkit-border-radius: 15px;
                border-radius: 15px;
            } 
              
             .Buttonhover
            {
                cursor:pointer;
                -moz-border-radius: 15px;
                -webkit-border-radius: 15px;
                border-radius: 15px;
            } 
    
    	#overlay 
            {
                ;
                z-index: 99;
                top: 0px;
                left: 0px;
                background-color: #f8f8f8;
                width: 100%;
                height: 100%;
                filter: Alpha(Opacity=90);
                opacity: 0.9;
                -moz-opacity: 0.9;
            }     
                   
            #theprogress 
            {
                background-color: #fff;
                border:1px none #ccc;
                padding:10px;
                width: 300px;
                height: 30px;
                line-height:30px;
                text-align: center;
                filter: Alpha(Opacity=100);
                opacity: 1;
                -moz-opacity: 1;
            }
    
            #modalprogress 
            {
                ;
                top: 40%;
                left: 50%;
                margin: -11px 0 0 -150px;
                color: #990000;
                font-weight:bold;
                font-size:28px;
                font-family:SC_AMEEN;  
            }
    
             
            .auto-style3 {
                color: red;
                text-align: right;
                font-style: normal;
                font-size: 24px;
            }
    
            .Panel1Style
            {
                margin-top:30px; 
                background-color:#C9DCF2;
                opacity: 0.8;
                Border-Color:Black; 
                Border-Style:Solid;
                Width:600px;
                -moz-border-radius: 15px;
                -webkit-border-radius: 15px;
                border-radius: 15px;
            }
    
           .modalBackground
            {
                background-color:black;
                filter:alpha(opacity=90);
                opacity:0.8;  
            }
    
           .auto-style31 {
                border: 1px solid Black;
                background-color: #96C2F2;
                height: 40px;
                text-align: right;
            }
    
           .auto-style34 {
                font-family: "sakkal Majalla";
                font-size: 28px;
            }
    
           .auto-style35 {
                text-align: right;
                font-size: 26px;
                font-weight:bold;   
                color: red;
                font-family: "Sakkal Majalla";
                font-style: normal;
                margin-left: 0px;
                margin-top: 5px;
            }
    
           .auto-style22 {
                height: 54px;
                text-align: center;
            }
    
           .CalenderStyle
            {
                background-color:white;  
                background-;  
                ;
            }
             
      </style>
    
    </asp:Content>
    <asp:Content ID="Content2" ContentPlaceHolderID="CpMainContent" Runat="Server">
        <script type="text/javascript">
    
            function OpenCCTargets() {
                window.open('CCPosting.aspx', '_blank')
            }
    
            function OpenTagsWindow() {
                window.open('TagsWindow.aspx', '_blank')
            }
    
            function OpenMultiple() {
                window.open('NewPostTargets.aspx', '_blank');
            }
    
            function SelectPrivatePersons() {
                window.open('PrivacyPersons.aspx', '_blank');
            }
    
            function OpenIncomingInfo() {
                window.open('IncomingPostInfo.aspx', '_blank');
            }
    
            function IsFileSelected() {
                if (document.getElementById("<%=AttachmentsSelecter.ClientID%>").value == "") {
                    document.getElementById("<%=AttachmentsSelecter.ClientID%>").style.color = "Transparent";
                    document.getElementById("<%=AttachmentsSelecter.ClientID%>").style.backgroundColor = "White";
                }
                else {
                    document.getElementById("<%=AttachmentsSelecter.ClientID%>").style.color = "black";
                    document.getElementById("<%=AttachmentsSelecter.ClientID%>").style.backgroundColor = "Green";
                }
                        
            }
    
        </script>
    
        <script type="text/javascript">
    
            //$(document).on("idle.idleTimer", function (event, elem, obj) {
            //    // Once the timer is idle (after 10 seconds), perform an event (your redirect)
            //    alert("Session has Expired.You will be required to relogin.");
            //    window.location.href = 'SessionExpiry.aspx';
            //});
    
           
            //$.idleTimer(1000);
    
        </script>
    
        <asp:toolkitscriptmanager ID="ScriptManager1" runat="server" />
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
        
                <div id="MainFields"  runat="server" class="MainFieldsDivStyle" >
    
                    <table id="NewPostingForm" runat="server" width="100%" >
                
                    <tr style="height:60px;" align="center"  >
                        <td colspan="6">
                            <asp:Label ID="Label6" runat="server" Font-Names="Sakkal Majalla" Height="42px" style="font-size: 38px; font-family: 'Sakkal Majalla';" Text="رســالة جديـــــدة"></asp:Label>
                        </td>
                        <td></td>
                    </tr>
                
                    <tr>
                    
                        <td align="right" width="5%">
                            <asp:CustomValidator ID="SenderNotUser" runat="server" 
                                ControlToValidate="sourcename" CssClass="ErrorMessage" 
                                ErrorMessage="إذا كانت المراسلة داخلية فالمرسل يجب أن يكون هو المستخدم نفسه" Width="12px">*</asp:CustomValidator>
                            <asp:CustomValidator ID="BothIdenticalValidator" CssClass="ErrorMessage" 
                                runat="server" ErrorMessage="المرسل يجب أن يكون مختلفا عن المستقبل" 
                                SetFocusOnError="True" Display="Dynamic" ControlToValidate="SourceName" Width="12px" >*</asp:CustomValidator>
                        </td>
                        <td width="5%">
                            <asp:Button ID="PickFromExEntity" runat="server" CausesValidation="False" ForeColor="White" Height="38px"   
                            Text="..." ToolTip="اضغط لاختيار الجهة الخارجية" UseSubmitBehavior="False" BackColor="#6262FF"
                            style="text-align: center; font-family: sc_AMEEN; font-size: 30px;" Width="35px"
                            onMouseOut="this.className='ButtonoutA'" onMouseOver="this.className='ButtonhoverA'" />
                        </td>
                        <td align="right" colspan="3" width="55%"  >
                            <asp:DropDownList ID="SourceName" runat="server" DataSourceID="SDS2" 
                            DataTextField="Name" DataValueField="Indx" Height="35px" 
                            style="text-align:right ;font-family: 'Sakkal Majalla'; font-size: 24px; margin-top: 0px; margin-bottom: 0px; border-style:solid; border-color:Black;  border-width:2px;
                            -moz-border-radius: 15px;-webkit-border-radius: 15px;border-radius: 15px; " 
                            Width="500px" BackColor="White" AutoPostBack="True" 
                            onMouseOver="this.className='Buttonhover'" onMouseOut="this.className='Buttonout'" />
    
                        </td>
                        <td align="right" class="LabelingCell" width="30%">
                            <asp:Label ID="FromLabel" runat="server" Text="مــــــــن" 
                                BorderStyle="None" BorderWidth="0px" ForeColor="Black" Height="35px" 
                                style="font-size: 30px; margin-right:5px; font-family: sc_AMEEN; text-align: right;" 
                                ></asp:Label>
                        </td>
                        <td width="5%"></td>
                    </tr>
                
    
                    <tr>
                        <td align="right" >
                            <asp:CustomValidator ID="NoneUserValidator" runat="server" 
                                ErrorMessage="المستخدم يجب أن يكون مرسلا أو مستقبلا" 
                                ControlToValidate="TargetName" CssClass="ErrorMessage"  
                                SetFocusOnError="True" Display="Dynamic">*</asp:CustomValidator>
                            <asp:CustomValidator ID="BothExternalValidator" runat="server" 
                                ErrorMessage="المرسل أو المستقبل يجب أن يكون من داخل الوزارة" 
                                ControlToValidate="TargetName" CssClass="ErrorMessage" 
                                SetFocusOnError="True" Display="Dynamic">*</asp:CustomValidator>
                        </td>
                        <td>
                            <asp:Button ID="PickToExEntity" runat="server" BackColor="#6262FF" CausesValidation="False" ForeColor="White" Height="38px" 
                                style="text-align: center; font-family: sc_AMEEN; font-size: 30px;" ToolTip="اضغط لاختيار الجهة الخارجية" UseSubmitBehavior="False" Width="35px"
                                onMouseOut="this.className='ButtonoutA'" onMouseOver="this.className='ButtonhoverA'" Text="..." />
                        </td>
                        <td align="right" colspan="2"  >
                            <asp:DropDownList ID="TargetName" runat="server" DataSourceID="SDS1"    
                            DataTextField="Name" DataValueField="Indx" Height="35px" 
                            style="text-align:right ;font-family: 'Sakkal Majalla'; font-size: 24px; margin-top: 0px; margin-bottom: 0px; border-style:solid; border-color:Black; 
                            border-width:2px;-moz-border-radius: 15px;-webkit-border-radius: 15px;border-radius: 15px;" 
                            Width="420px" BackColor="White" AutoPostBack="True"
                            onMouseOver="this.className='Buttonhover'" onMouseOut="this.className='Buttonout'" />
                        </td>
                        <td align="right">
                            <asp:radiobutton ID="AloneCB" AutoPostBack="True"  runat="server" style="font-family: 'sakkal Majalla'; font-size: 24px;" Text="واحد" TextAlign="Left" Width="75px" Height="35px" />
                        </td>
                        <td align="right" class="LabelingCell" rowspan="2">
                            <asp:Label ID="ToLabel" runat="server" Text="إلـــــــى" 
                                BorderStyle="None" BorderWidth="0px" ForeColor="Black" Height="30px" 
                                style="font-size: 30px; margin-right:5px; font-family: sc_AMEEN; text-align: right;" 
                                BorderColor="Black" ></asp:Label>
                        </td>
                        <td></td>
                    </tr>
                           
                    <tr>
                        <td align="right" >
                            <asp:CustomValidator ID="NoMultiTargetsSelected" runat="server" 
                                ErrorMessage="عند اختيار &quot;متعدد&quot; فيجب إضافة مستلم أو أكثر في القائمة التي ستظهر بالضغط على الزر المقابل" 
                                ControlToValidate="TargetName" CssClass="ErrorMessage" 
                                SetFocusOnError="True" Display="Dynamic">*</asp:CustomValidator>
                        </td>
                        <td>
                            &nbsp;</td>
                        <td align="right" colspan="2" >
                            <asp:Button ID="OpenMultiTargets" runat="server" BackColor="#999999" AutoPostBack="true" 
                                style="font-size: 30px; margin-left: 30px; font-family: sc_AMEEN; text-align: center;" Height="38px" ForeColor="White" Width="35px" CausesValidation="False" UseSubmitBehavior="False" OnClientClick="OpenMultiple()"
                                onMouseOver="this.className='ButtonhoverA'" onMouseOut="this.className='ButtonoutA'" Text="..." />
                        </td>
                        <td align="right">
                            <asp:radiobutton ID="MultiCB" AutoPostBack="True"  runat="server" style="font-family: 'sakkal Majalla'; font-size: 24px" Text="متعدد" TextAlign="Left" Width="75px" Height="35px" />
                        </td>
                        <td></td>
                    </tr>
                           
                    <tr>
                        <td style="text-align: right" >
                            <asp:CustomValidator ID="SavedDraftLetterID" runat="server" ControlToValidate="TargetName" CssClass="ErrorMessage" Display="Dynamic" ErrorMessage="يمكنك تغيير رقم الرسالة بعد حفظ مسودة الرسالة" SetFocusOnError="True">*</asp:CustomValidator>
                        </td>
                        <td>
                            <asp:Button ID="EditLetterID" runat="server" BackColor="#6262FF" CausesValidation="False" ForeColor="White" Height="38px" 
                                onMouseOut="this.className='ButtonoutA'" onMouseOver="this.className='ButtonhoverA'" 
                                style="font-size: 30px; text-align: left; font-family: sc_AMEEN;" ToolTip="اضغط لتغيير رقم الرسالة" UseSubmitBehavior="False" Width="35px" Text="..." />
                        </td>
                        <td align="right" colspan="3">
                            <asp:textbox ID="LetterIDTxtBox" runat="server" Height="35px"  
                            style="font-family: 'sakkal Majalla'; font-size: 30px; text-align: center; margin-top: 0px; border-style:solid; border-color:Black;
                            -moz-border-radius: 15px;-webkit-border-radius: 15px;border-radius: 15px;" 
                            Width="495px" ForeColor="#0061C1" ReadOnly="True"  ></asp:textbox>
                        </td>
                        <td align="right" class="LabelingCell">
                            <asp:Label ID="LetterIDLabel" runat="server" Text="رقم الرسالة" 
                                BorderStyle="None" BorderWidth="0px" ForeColor="Black" Height="30px" 
                            
                                style="font-size: 30px; margin-right:5px;  font-family: sc_AMEEN; text-align: right;" 
                                BorderColor="Black" Width="110px" 
                                ></asp:Label>
                        </td>
                        <td></td>
                    </tr>
        
                    <tr>
                        <td style="text-align: right" >
                            <asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="TargetName" CssClass="ErrorMessage" Display="Dynamic" ErrorMessage="يمكنك تغيير رقم الرسالة بعد حفظ مسودة الرسالة" SetFocusOnError="True">*</asp:CustomValidator>
                        </td>
                        <td>
                            <%--<asp:Button ID="EditFollowUpID" runat="server" BackColor="#6262FF" CausesValidation="False" ForeColor="White" Height="38px" 
                                onMouseOut="this.className='ButtonoutA'" onMouseOver="this.className='ButtonhoverA'" 
                                style="font-size: 30px; text-align: left; font-family: sc_AMEEN;" ToolTip="اضغط لتغيير رقم الرسالة" UseSubmitBehavior="False" Width="35px" Text="..." />--%>
                        </td>
                        <td align="right" colspan="3">
                            <asp:textbox ID="FollowUpID" runat="server" Height="35px"  
                            style="font-family: 'sakkal Majalla'; font-size: 30px; text-align: center; margin-top: 0px; border-style:solid; border-color:Black;
                            -moz-border-radius: 15px;-webkit-border-radius: 15px;border-radius: 15px;" 
                            Width="495px" ForeColor="#0061C1" ReadOnly="True"  ></asp:textbox>
                        </td>
                        <td align="right" class="LabelingCell">
                            <asp:Label ID="Label7" runat="server" Text="رقم المتابعة" 
                                BorderStyle="None" BorderWidth="0px" ForeColor="Black" Height="30px" 
                            
                                style="font-size: 30px; margin-right:5px;  font-family: sc_AMEEN; text-align: right;" 
                                BorderColor="Black" Width="110px" 
                                ></asp:Label>
                        </td>
                        <td></td>
                    </tr>
                                                
                    <tr>
                        <td align="right" >
                            <asp:RequiredFieldValidator ID="SubjectRequiredValidator" runat="server" 
                                ErrorMessage="لم تقم بإدخال الموضوع" ControlToValidate="SubjectTxtBox" 
                                CssClass="ErrorMessage" SetFocusOnError="True" Display="Dynamic"
                                >*</asp:RequiredFieldValidator>
                        </td>
                        <td></td>
                        <td align="right" colspan="3">
                        
                            <asp:textbox ID="SubjectTxtBox" runat="server" Height="35px"
                                style="font-family: 'Sakkal Majalla'; font-size: 22px; text-align: right; margin-top: 0px; border-style:solid; border-color:Black;
                                -moz-border-radius: 15px;-webkit-border-radius: 15px;border-radius: 15px;" Width="495px"></asp:textbox>
                        </td>
                        <td align="right" class="LabelingCell">
                            <asp:Label ID="SubjectLabel" runat="server" Text="الموضــوع" 
                            BorderStyle="None" BorderWidth="0px" ForeColor="Black" Height="35px" 
                            style="font-size: 30px; margin-right:5px;  font-family: sc_AMEEN; text-align: right;" 
                                BorderColor="Black" Width="110px" 
                            ></asp:Label>
                        </td>
                        <td></td>
                    </tr>
    
                    <tr>
                        <td>
                        </td>
                        <td></td>
                        <td align="right" colspan="3">
                            <asp:TextBox ID="CommentsTxtBox" runat="server" TextMode="MultiLine" Height="100px"
                            Width="490px" BorderColor="Black" BorderStyle="Solid" BorderWidth="2px"  
                            Style="font-size: 22px; font-family: 'Sakkal Majalla'; text-align: right;
                            -moz-border-radius: 15px;-webkit-border-radius: 15px;border-radius: 15px;"></asp:TextBox>
                        </td>
                        <td align="right" class="LabelingCell">
                            <asp:Label ID="CommentsLabel" runat="server" Text="التعليق / الملاحظات" 
                            BorderStyle="None" BorderWidth="0px" ForeColor="Black" Height="74px" 
                            style="font-size: 30px; margin-right:5px;  font-family: sc_AMEEN; text-align: right;" 
                                BorderColor="Black" 
                            ></asp:Label>
                        </td>
                        <td></td>
                    </tr>
    
                    <tr style="height:40px;">
                        <td>
                        </td>
                        <td align="right">
                        </td>
                        <td align="right" colspan="2">
                        </td>
                        <td align="right">
                            <asp:radiobutton ID="NowDate" runat="server" AutoPostBack="True" Height="35px" style="font-family: 'sakkal Majalla'; font-size: 24px;" Text="الآن" TextAlign="Left" />
                        </td>
                        <td align="right" class="LabelingCell" rowspan="2">
                            <asp:Label ID="Label5" runat="server" Text="تاريخ الرسالة" 
                                BorderStyle="None" BorderWidth="0px" ForeColor="Black" Height="30px" 
                            
                                style="font-size: 30px; margin-right:5px; font-family: sc_AMEEN; text-align: right;" 
                                BorderColor="Black" Width="110px" ></asp:Label>
                        </td>
                        <td></td>
                    </tr>
                           
                    <tr>
                        <td align="right" >
                            <asp:CustomValidator ID="NowToPostDateValidator" runat="server" 
                                ErrorMessage="تاريخ الرسالة يجب أن لا يكون أكبر من تاريخ اليوم" 
                                ControlToValidate="TargetName" CssClass="ErrorMessage" 
                                SetFocusOnError="True" Display="Dynamic" Width="12px">*</asp:CustomValidator>
                        </td>
                        <td></td>
                        <td align="right" width="250px" >
                            <asp:ImageButton ID="imgPopup" runat="server" Height="30px" ImageAlign="Bottom" ImageUrl="~/Images/Calender.png" Width="26px" CausesValidation="False" />
                        </td>
                        <td align="right">
                            <asp:TextBox ID="PostDateTxtBox" runat="server" Height="32px" style="border:solid black 2px; font-family: 'sakkal Majalla'; font-size: 24px; text-align: right;
                            -moz-border-radius: 15px;-webkit-border-radius: 15px;border-radius: 15px;" Width="165px"></asp:TextBox>
                            <asp:CalendarExtender ID="Calendar1" runat="server" Format="dd-MMMM-yyyy" PopupButtonID="imgPopup" TargetControlID="PostDateTxtBox">
                            </asp:CalendarExtender>
                        </td>
                        <td align="right">
                            <asp:radiobutton ID="OtherDate" AutoPostBack="True"  runat="server" style="font-family: 'sakkal Majalla'; font-size: 24px" Text="آخـــــــر" TextAlign="Left" Width="75px" Height="35px" />
                            </td>
                        <td></td>
                    </tr>
    
    
                    <tr>
                        <td align="right"  >
                            <asp:CustomValidator ID="NoRequestMultiTargets" CssClass="ErrorMessage" 
                                SetFocusOnError="true"   runat="server" Display="Dynamic" 
                                ControlToValidate="RAPTmpTxt" ErrorMessage="إذا كان نوع الرسالة &quot;طلب&quot; فإن المرسل إليه يجب أن يكون واحد و ليس متعدد" Width="12px">*</asp:CustomValidator>
                        </td>
                        <td></td>
                         <td align="right" colspan="3">
                            <asp:DropDownList ID="PostTypeDDL" runat="server" Height="35px"
                            style="text-align:right ;font-family: 'sakkal Majalla'; margin-top:0px;font-size: 24px; text-align: right; border-style:solid; border-color:Black; border-width:2px;
                            -moz-border-radius: 15px;-webkit-border-radius: 15px;border-radius: 15px;" 
                            Width="120px" DataSourceID="SDS4" DataTextField="PostType" DataValueField="PostType" AutoPostBack="True"
                            onMouseOver="this.className='Buttonhover'" onMouseOut="this.className='Buttonout'">
                             </asp:DropDownList>    
    
                        </td>
                        <td align="right" class="LabelingCell">
                            <asp:Label ID="PTypeLabel" runat="server" Text="نوع الرسالة" 
                            BorderStyle="None" BorderWidth="0px" ForeColor="Black" Height="35px" 
                            style="font-size: 30px; margin-right:5px;  font-family: sc_AMEEN; text-align: right;" 
                                BorderColor="Black" Width="110px" 
                            ></asp:Label>
                        </td>
                        <td></td>
                    </tr>
    
                    <tr>
                        <td align="right">
                            <asp:RegularExpressionValidator ID="RAPValidator" runat="server" ControlToValidate="RAPTxtBox" Display="Dynamic" ErrorMessage="مهلة الرد غير صحيحة" SetFocusOnError="True" style="font-size: 26px" ValidationExpression="^[0-9]+$" Width="12px">*</asp:RegularExpressionValidator>
                            <%--<asp:CustomValidator ID="RAPCustomeValidator" CssClass="ErrorMessage" 
                                SetFocusOnError="true"   runat="server" Display="Dynamic" 
                                ControlToValidate="RAPTmpTxt" ErrorMessage="لم تقم بإدخال مهلة الرد">*</asp:CustomValidator>--%>
                        </td>
                        <td></td>
                         <td align="right" colspan="3">
                            <asp:textbox ID="RAPTxtBox" runat="server" Height="30px"
                            style="font-family: verdana, Geneva, Tahoma, sans-serif; margin-top:0px; font-size: 22px; text-align: center; border-style:solid; border-color:Black;
                            -moz-border-radius: 15px;-webkit-border-radius: 15px;border-radius: 15px;" 
                            Width="115px"></asp:textbox>
                        </td>
                        <td align="right" class="LabelingCell">
                            <asp:Label ID="RAPLabel" runat="server" Text="مهلة الرد - يوم" 
                            BorderStyle="None" BorderWidth="0px" ForeColor="Black" Height="35px" 
                            style="font-size: 30px; margin-right:5px;  font-family: sc_AMEEN; text-align: right;" 
                                BorderColor="Black" Width="110px" 
                            ></asp:Label>
                        </td>
                        <td></td>
                    </tr>
    
              
                    <tr>
                        <td >
                        </td>
                        <td></td>
                        <td align="right" colspan="3"  >
                            <asp:DropDownList ID="ImportanceDD" runat="server" Height="35px"
                            style="text-align:right;font-family: 'sakkal Majalla';margin-top:0px; font-size: 24px; text-align: right; border-style:solid; border-color:Black;border-width:2px;
                            -moz-border-radius: 15px;-webkit-border-radius: 15px;border-radius: 15px;" 
                            Width="120px" DataSourceID="SDS3" DataTextField="Importance" DataValueField="Importance"
                            onMouseOver="this.className='Buttonhover'" onMouseOut="this.className='Buttonout'">
                             </asp:DropDownList>
                        </td>
                        <td align="right" class="LabelingCell">
                            <asp:Label ID="Label1" runat="server" Text="الأهمية" 
                            BorderStyle="None" BorderWidth="0px" ForeColor="Black" Height="35px" 
                            style="font-size: 30px; margin-right:5px;  font-family: sc_AMEEN; text-align: right;" 
                            BorderColor="Black" Width="110px" >
                            </asp:Label>
                        </td>
                        <td></td>
                    </tr>
    
                
                
                    <tr>
    
                        <td align="right" >
                            <%--<asp:RequiredFieldValidator ID="AttachmentRequired" runat="server" ControlToValidate="AttachmentsSelecter" CssClass="auto-style2" Display="Dynamic" ErrorMessage="لم تقم باختيار الملف المرفق" SetFocusOnError="True">*</asp:RequiredFieldValidator>--%>
                            <asp:CustomValidator ID="AttachmentFilesCount" runat="server" SetFocusOnError="true"  
                                 display="Dynamic" CssClass="auto-style3"  
                                ErrorMessage="عدد الملفات المرفقة يجب أن لا يتجاوز خمسة ملفات">*</asp:CustomValidator>
                            <asp:CustomValidator ID="AttachmentRequiredFile" runat="server" 
                                ErrorMessage="لم تقم باختيار أي ملف مرفق" 
                                CssClass="auto-style3" SetFocusOnError="true" Display="Dynamic">*</asp:CustomValidator>
                            <asp:CustomValidator ID="AttachmentFileType" runat="server" 
                                ErrorMessage="نوع إحدى المرفقات التي قمت باختيارها غير صحيح" OnServerValidate="AttachmentValidator1" 
                                CssClass="auto-style3" SetFocusOnError="True" Display="Dynamic">*</asp:CustomValidator>
                        </td>
                        <td></td>
                        <td align="right" colspan="3">
                        
                            <asp:FileUpload ID="AttachmentsSelecter" runat="server" onchange="IsFileSelected()"  
                            Width="495px" BorderColor="Black" BorderStyle="Solid" 
                            Height="35px" BackColor="White" BorderWidth="2px" 
                            style="font-size: 22px; font-family: 'sakkal Majalla';
                            -moz-border-radius: 15px;-webkit-border-radius: 15px;border-radius: 15px;" 
                            cssclass="FileUploadStyle" AllowMultiple="True" />
                            <br />
    
    
                            <asp:TextBox ID="RAPTmpTxt" runat="server" Visible="False" Width="1px">Scratch</asp:TextBox>
                        
                            <asp:TextBox ID="TmpTxt" runat="server" Visible="False" Width="1px">Scratch</asp:TextBox>
                        
                        </td>
                        <td align="right" class="LabelingCell" >
                            <asp:Label ID="AttachmentLabel" runat="server" Text="المرفقات" 
                            BorderStyle="None" BorderWidth="0px" ForeColor="Black" Height="35px" 
                            style="font-size: 30px; margin-right:5px;  font-family: sc_AMEEN; text-align: right;" Width="110px" 
                            ></asp:Label>
                        </td>
                        <td></td>
                    </tr>
                    
      
                    <tr>
                        <td align="right"  >
                            <asp:CustomValidator ID="IncomingInfoValidator" runat="server" ControlToValidate="TargetName" CssClass="ErrorMessage" Display="Dynamic" SetFocusOnError="True" ErrorMessage="معلومات المرجع والتاريخ المرافق يجب أن تكون فارغة لأن المرسل من داخل الوزارة" Width="12px">*</asp:CustomValidator>
                        </td>
                          <td></td>
    
                        <td align="right" colspan="3">
                            <%--<asp:Button ID="OpenIncomingInfoWindow" runat="server" BackColor="#6262FF" style="font-size: 30px; text-align: center; font-family: sc_AMEEN;" Height="35px" ForeColor="White" CausesValidation="False" Width="35px" OnClientClick="OpenIncomingInfo()" UseSubmitBehavior="False"
                            onMouseOver="this.className='ButtonhoverA'" onMouseOut="this.className='ButtonoutA'" Text="..." />--%>
                            <asp:Button ID="OpenIncomingInfoWindow" runat="server" BackColor="#6262FF" style="font-size: 30px; text-align: center; font-family: sc_AMEEN;" Height="35px" ForeColor="White" CausesValidation="False" Width="35px" UseSubmitBehavior="False"
                            onMouseOver="this.className='ButtonhoverA'" onMouseOut="this.className='ButtonoutA'" Text="..." />
                            <asp:Label ID="Panel1DummyLabel" runat="server" Text=" " />
                        </td>
                        <td align="right" class="LabelingCell"  >
                            <asp:Label ID="Label4" runat="server" BorderStyle="None" BorderWidth="0px" ForeColor="Black" Height="35px" style="font-size: 26px;  font-family: sc_AMEEN;" Text="المرجع والتاريخ المرافق"></asp:Label>
                        </td>
                        <td></td>
                    </tr>
                
            
                
    
    
                    <tr>
                        <td>
                         </td>
                          <td></td>
                        <td align="right" colspan="3" >
                            <asp:Button ID="OpenTagsWindow" runat="server" BackColor="#6262FF" style="font-size: 30px; text-align: center; font-family: sc_AMEEN;" Height="35px" ForeColor="White" CausesValidation="False" Width="35px" OnClientClick="OpenTagsWindow()" UseSubmitBehavior="False"
                             onMouseOver="this.className='ButtonhoverA'" onMouseOut="this.className='ButtonoutA'" Text="..." />
                        </td>
                        <td align="right" class="LabelingCell">
                            <asp:Label ID="Label2" runat="server" Text="الكلمات المفتاحية" 
                            BorderStyle="None" BorderWidth="0px" ForeColor="Black" Height="35px" 
                            style="font-size: 30px; margin-right:5px;  font-family: sc_AMEEN; text-align: center;" 
                            ></asp:Label>
                        </td>
                        <td></td>
                    </tr>
                    <tr>
                        <td align="right" >
                            <asp:CustomValidator ID="SenderAndCCTargetExternalEntities" runat="server" ControlToValidate="TargetName" CssClass="ErrorMessage" Display="Dynamic" ErrorMessage="لا يمكن إرسال نسخة إلى جهة خارج الوزارة عندما يكون المرسل من خارح الوزارة أيضا" SetFocusOnError="True" Width="12px">*</asp:CustomValidator>
                        </td>
                        <td></td>
    
                        <td align="right" colspan="3" >
                            <asp:Button ID="OpenCCWindow" runat="server" BackColor="#6262FF" style="font-size: 30px; text-align: center; font-family: sc_AMEEN;" Height="35px" ForeColor="White" CausesValidation="False" Width="35px" OnClientClick="OpenCCTargets()" UseSubmitBehavior="False"
                                onMouseOver="this.className='ButtonhoverA'" onMouseOut="this.className='ButtonoutA'" Text="..." />
                        </td>
                        <td align="right" class="LabelingCell" >
                            <asp:Label ID="CCPosting" runat="server" Text="إرسال نسخة" 
                            BorderStyle="None" BorderWidth="0px" ForeColor="Black" Height="35px" 
                            style="font-size: 30px; margin-right:5px;  font-family: sc_AMEEN; text-align: center;" 
                            ></asp:Label>
                        </td>
                        <td></td>
                    </tr>
            
                    <tr>
                        <td align="right" >
                            <asp:CustomValidator ID="PrivacyMessageValidator" runat="server" ControlToValidate="TargetName" CssClass="ErrorMessage" Display="Dynamic" ErrorMessage="يجب اختيار الأشخاص المخولين للإطلاع على الرسالة لأنها سرية" SetFocusOnError="True" Width="12px">*</asp:CustomValidator>
                        </td>
                          <td></td>
                        <td align="right" colspan="2">
                            <asp:CheckBox ID="IsTopSecret" runat="server" Height="36px" style="font-family: 'sakkal Majalla'; font-size: 24px; color: #0000CC;" Text="هذه الرسالة خاصة وسرية" TextAlign="Left" />
                        </td>
                        <td align="right">
                            <asp:Button ID="PrivateUsers" runat="server" BackColor="#6262FF" CausesValidation="False" ForeColor="White" Height="35px" OnClientClick="SelectPrivatePersons()" style="font-size: 30px; text-align: center; font-family: sc_AMEEN;" UseSubmitBehavior="False" Width="35px"
                            onMouseOver="this.className='ButtonhoverA'" onMouseOut="this.className='ButtonoutA'" Text="..." />
                        </td>
                        <td align="right" class="LabelingCell">
                            <asp:Label ID="Label3" runat="server" Text="الخصوصية" 
                            BorderStyle="None" BorderWidth="0px" ForeColor="Black" Height="35px" 
                            style="font-size: 30px; margin-right:5px;  font-family: sc_AMEEN; text-align: center;" 
                            ></asp:Label>
                        </td>
                        <td></td>
                    </tr>
    
               
    
                    <tr align="center"  >
                        <td colspan="7">
                            <asp:Button ID="OpenDraft" runat="server" BackColor="#6262FF" ForeColor="White" Height="40px" style="text-align: center; font-size: 30px; margin-top: 46px; margin-bottom: 5px; font-family: sc_AMEEN; margin-left: 11px;
                            -moz-border-radius: 15px;-webkit-border-radius: 15px;border-radius: 15px;" Text="اختيار المسودة" Width="200px" CausesValidation="False" UseSubmitBehavior="False"
                            onMouseOver="this.className='Buttonhover'" onMouseOut="this.className='Buttonout'" />
                            <asp:Button ID="SaveAsDraft" runat="server" BackColor="#6262FF" ForeColor="White" Height="40px" style="text-align: center; font-size: 30px; margin-top: 46px; margin-bottom: 5px; font-family: sc_AMEEN; margin-left: 44px;
                            -moz-border-radius: 15px;-webkit-border-radius: 15px;border-radius: 15px;" Text="حفظ المسودة" Width="200px" UseSubmitBehavior="False"
                            onMouseOver="this.className='Buttonhover'" onMouseOut="this.className='Buttonout'" />
                            <asp:Button ID="PostNewLetter" runat="server" BackColor="#6262FF" ForeColor="White" Height="40px" style="text-align: center; font-size: 30px; margin-top: 46px; margin-bottom: 5px; font-family: sc_AMEEN; margin-left: 44px;
                            -moz-border-radius: 15px;-webkit-border-radius: 15px;border-radius: 15px; " Text="أرسـل" Width="200px"
                            onMouseOver="this.className='Buttonhover'" onMouseOut="this.className='Buttonout'" UseSubmitBehavior="False" />
                        </td>
                    </tr>
    
               
                    <tr>
                        <td colspan="7" align="left" style="height:50px;"  >
                            <asp:ImageButton ID="CloseThisPage" runat="server" Height="40px" ImageUrl="~/Images/CloseThisPage.png" onMouseOut="this.className='Buttonout'" onMouseOver="this.className='Buttonhover'" style="margin-left: 1px; margin-top: 30px;" Width="50px" CausesValidation="False" />
                        </td>
                    </tr>
                    
    
                </table> 
        
                    <table id="ValidationSummaryTable" runat="server" width="98%">  
                    <tr>
                    
                        <td rowspan="5" align="right">
                            <asp:ValidationSummary ID="ValidationSummary1" runat="server" 
                            CssClass="FooterErrorMessage" DisplayMode="List" 
                            Height="144px"  />
                        </td>
                     
                    </tr>
    
                </table> 
    
                </div>
                    
    
            <asp:Panel ID="Panel1" runat="server" CssClass="Panel1Style" style="display:none" >
                <table id="MessageTable" runat="server" style="width:100%;">
                    
                    <tr>
                        <td align="left">
                            <asp:ImageButton ID="Panel1Cancel" runat="server" Height="16px" ImageUrl="~/Images/NewClose.png" Width="20px" CausesValidation="False" />
                        </td>
                    </tr>
                    
                    <tr align="center" style="height:60px;">
                        <td colspan="5">
                            <asp:Label ID="Label8" runat="server" style="font-family: 'sakkal Majalla'; font-size: 30px" Text="المعلومات الواردة مع الرسالة"></asp:Label>
                        </td>
                    </tr>
    
                    <tr style="height:35px;" >
                        <td width="10%"></td>
                        <td width="5%">
                        </td>
                        <td>
                            <asp:TextBox ID="Panel1PostRefNo" runat="server" BorderColor="Black" BorderStyle="Solid" Height="32px" style="border:solid black 1px; font-family: 'sakkal Majalla'; font-size: 24px; text-align: right;border-color:black;border-style:solid;border-width:1px;
                                -moz-border-radius: 15px;-webkit-border-radius: 15px;border-radius: 15px;" Width="275px"></asp:TextBox>
                        </td>
                        <td class="auto-style31" width="25%">
                            <asp:Label ID="Label9" runat="server" Text="مرجع الرسالة" CssClass="auto-style34"></asp:Label>
                        </td>
                        <td width="10%" class="auto-style30"></td>
                    </tr>
    
                        <tr>
                        <td align="right">
                            <asp:CustomValidator ID="IncomingDateValidator" runat="server" 
                                Display="Dynamic" ErrorMessage="التاريخ يجب أن لا يكون بعد تاريخ اليوم" 
                                style="font-size: 28px; color: #FF0000; " ValidationGroup="Panel1VG">*</asp:CustomValidator>
                        </td>
                        <td style="text-align: right;">
                            <asp:ImageButton ID="Panel1imgPopup" runat="server" Height="32px" ImageAlign="Right" ImageUrl="~/Images/Calender.png" Width="35px" ValidationGroup="Panel1VG" />
                        </td>
                            <td >
                                <asp:TextBox ID="Panel1IncomingDateValue" runat="server" Height="32px" 
                                    style="border:solid black 1px; font-family: 'sakkal Majalla'; font-size: 24px; text-align: right;border-color:black;border-style:solid;border-width:1px;
                                    -moz-border-radius: 15px;-webkit-border-radius: 15px;border-radius: 15px;" Width="275px"></asp:TextBox>
                                <asp:CalendarExtender ID="Panel1CalendarExtender1" runat="server" PopupButtonID="Panel1imgPopup" TargetControlID="Panel1IncomingDateValue" Format="dd-MMMM-yyyy" CssClass="CalenderStyle" ></asp:CalendarExtender>
                            </td>
                        <td class="auto-style31">
                            <asp:Label ID="Label10" runat="server" CssClass="auto-style34" Text="تاريخ الرسالة"></asp:Label>
                        </td>
                        <td></td>
                    </tr>
    
                    <tr align="center">
                        <td align="center" colspan="5" class="auto-style22">
                            
                            <asp:Button ID="OKbtn" runat="server" BackColor="#6262FF"   ForeColor="White" Height="38px" 
                                style="text-align: center; font-size: 28px; font-family: sc_AMEEN;margin-top:25px; margin-bottom: 5px; -moz-border-radius: 15px;-webkit-border-radius: 15px;border-radius: 15px;" Text="حفظ" Width="200px"
                                onMouseOver="this.className='Buttonhover'" onMouseOut="this.className='Buttonout'" ValidationGroup="Panel1VG"  />
                        </td>
                    </tr>
                                    
                    
    
                </table>  
                <table id="Panel1validationtable" runat="server" width="100%">
                    <tr>
                        <td colspan="3" style="text-align: right" >
                            <asp:ValidationSummary ID="Panel1ValidationSummary" runat="server" CssClass="auto-style35" DisplayMode="List" ForeColor="#CC0000" Height="62px" Width="483px" ValidationGroup="Panel1VG" />
                        </td>
                    </tr>
                </table>
            </asp:Panel>
    
            <asp:ModalPopupExtender ID="ModalPopupExtender1" runat="server" CancelControlID="Panel1Cancel" PopupControlID="Panel1" DropShadow="true" TargetControlID="Panel1DummyLabel" BackgroundCssClass="modalBackground">
            </asp:ModalPopupExtender>
    
        </ContentTemplate> 
        <Triggers>
            <asp:PostBackTrigger ControlID="PostNewLetter" />
        </Triggers>
        </asp:UpdatePanel>     
    
        <asp:UpdateProgress ID="prgLoadingStatus" runat="server" DynamicLayout="true">
    	<ProgressTemplate>
            <div id="overlay">
                <div id="modalprogress">
                    <div id="theprogress">
                        <asp:Image ID="imgWaitIcon" runat="server" ImageAlign="AbsMiddle" ImageUrl="~/images/WaitingImage.gif" Height="100px" Width="100px" />
                        <br />
                        الرجاء الانتظار
                    </div>
                </div>
            </div>
        </ProgressTemplate>
        </asp:UpdateProgress>    
        
        <div id="ExtraItems"  runat="server" visible="false" >
            <table id="TmpTable" runat="server">   
                <tr>
                    <td>
                        <asp:SqlDataSource ID="SDS1" runat="server" 
                        ConnectionString="<%$ ConnectionStrings:TrackingConnectionString %>" 
                        SelectCommand="SELECT DISTINCT NewToTargets.Name, NewToTargets.Indx FROM NewToTargets WHERE (NewToTargets.LoadedByUserName = @LoadedByUserName) AND (NewToTargets.Name is not null) ORDER BY NewToTargets.Indx">
                        <SelectParameters>
                            <asp:SessionParameter Name="LoadedByUserName" SessionField="UserName" 
                                Type="String" />
                        </SelectParameters>
                        </asp:SqlDataSource>
                        <asp:SqlDataSource ID="SDS2" runat="server" 
                        ConnectionString="<%$ ConnectionStrings:TrackingConnectionString %>" 
                        SelectCommand="SELECT DISTINCT NewFromTargets.Name, NewFromTargets.Indx FROM NewFromTargets WHERE (NewFromTargets.LoadedByUserName = @LoadedByUserName) ORDER BY NewFromTargets.Indx">
                        <SelectParameters>
                            <asp:SessionParameter Name="LoadedByUserName" SessionField="UserName" 
                                Type="String" />
                        </SelectParameters>
                        </asp:SqlDataSource>
                        <asp:SqlDataSource ID="SDS3" runat="server" 
                        ConnectionString="<%$ ConnectionStrings:TrackingConnectionString %>" 
                        SelectCommand="SELECT DISTINCT [Importance], [ImportValue] FROM [ImportanceSource]">
                        </asp:SqlDataSource>
                        <asp:SqlDataSource ID="SDS4" runat="server" 
                        ConnectionString="<%$ ConnectionStrings:TrackingConnectionString %>" 
                        SelectCommand="SELECT DISTINCT * FROM [PostTypeSource]">
                        </asp:SqlDataSource>
                        <asp:SqlDataSource ID="SDS5" runat="server" 
                        ConnectionString="<%$ ConnectionStrings:TrackingConnectionString %>" 
                        SelectCommand="SELECT DISTINCT [KeyTag],[AdditionStatus],[AddRemove], [LoadedByUserName] FROM [AllTagsTemp] WHERE ([LoadedByUserName] = @LoadedByUserName)">
                            <SelectParameters>
                                <asp:SessionParameter Name="LoadedByUserName" SessionField="UserName" Type="String" />
                            </SelectParameters>
                        </asp:SqlDataSource>
    
                       
                    </td> 
                </tr>
    
                <tr>
                    <td>
                        <asp:GridView ID="GridView1" runat="server" Height="94px" Visible="False" Width="62px" DataSourceID="SDS5">
                            <Columns>
    
        
                                <asp:TemplateField Visible="false" >
                                    <ItemTemplate>
                                        <asp:Label ID="KeyTagField" runat="server" text='<%# Eval("KeyTag")%>'  />  
                                    </ItemTemplate>
                                </asp:TemplateField>
    
                                <asp:TemplateField Visible="false" >
                                    <ItemTemplate>
                                        <asp:Label ID="AddRemoveField" runat="server" text='<%# Eval("AddRemove")%>'  />  
                                    </ItemTemplate>
                                </asp:TemplateField>
    
                                
    
                                <asp:TemplateField Visible="false" >
                                    <ItemTemplate>
                                        <asp:Label ID="AdditionStatusField" runat="server" text='<%# Eval("AdditionStatus")%>'  />  
                                    </ItemTemplate>
                                </asp:TemplateField>
    
                                <asp:TemplateField Visible="false" >
                                    <ItemTemplate>
                                        <asp:Label ID="UNField" runat="server" text='<%# Eval("LoadedByUserName")%>'   />  
                                    </ItemTemplate>
                                </asp:TemplateField>
    
                            </Columns>
                        </asp:GridView>
                    </td>
                </tr>
            </table>
            
         </div>
    
    
    
    </asp:Content>
    
    

    My code-behind code:

    Imports System.Data
    Imports System.Data.SqlClient
    Imports System.Configuration
    Imports System.Diagnostics
    Imports System.IO
    Partial Class NewPosting_NewLetterPosting
        Inherits System.Web.UI.Page
        Public Shared ForwardingFieldsReader As SqlDataReader
        Public Shared UserName As String
        Public Shared PostDate As DateTime
        Public Shared PostDateStr As String
        Public Shared TodayDate As DateTime
        Public Shared StorageUnit As Integer
        Public Shared LetterIDPublic As String
        Public Shared SourceIndx As Long
        Public Shared TargetIndx As Long
        Public Shared ReqdAnsPeriod As Long
        Public Shared PostingTime As DateTime
        Public Shared AttachmentTypeError As Integer
        Public Shared InfoCopyPostConsecutive As Integer = 0
    
        Public Shared TheAttachedFileServerPath As String
    
        Public Shared UserIndx As Integer
        Public Shared Importance As String
        Public Shared UnitIndx As Integer
        Public Shared UpperLevelIndx As Integer
        Public Shared queryString As String
        Public Shared LoginingIndx As Integer
        'Public Shared EnabledColor As System.Drawing.Color = System.Drawing.ColorTranslator.FromHtml("#CCCCCC")
        Public Shared EnabledColor As System.Drawing.Color = System.Drawing.ColorTranslator.FromHtml("#6262FF")
        Public Shared DisabledColor As System.Drawing.Color = System.Drawing.ColorTranslator.FromHtml("#999999")
        Public Shared LoggingUserIndx As Integer
        Public Shared MultiCBUncheckable As Integer = 0
        Public Shared InRefNo As String = ""
        Public Shared InPostDate As Date = Date.Parse("01-01-1900")
        Public Shared UserUnitIndx As Integer
        Public Shared PerformValidation As Integer
        Public Shared DontValidate As Integer
    
    
    
        Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    
            If Session("UserName") = "" Then
                Response.Redirect("~\Logon\LogonScreen.aspx")
            End If
    
            Session("contentpage") = "NewLetterPosting"
    
    
    
            If IsPostBack = False Then
    
                Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
                Using connection As New SqlConnection(conString)
    
                    MultiCBUncheckable = 0
                    connection.Open()
    
                    If AttachmentsSelecter.FileName = "" Then
                        AttachmentsSelecter.BackColor = Drawing.Color.White
                        AttachmentsSelecter.ForeColor = Drawing.Color.White
                    End If
    
                    AttachmentTypeError = 1
    
                    UserName = Session("username")
                    SourceName.Enabled = True
                    TargetName.Enabled = True
                    PickFromExEntity.Enabled = True
                    PickFromExEntity.BackColor = EnabledColor
                    PickToExEntity.Enabled = True
                    PickToExEntity.BackColor = EnabledColor
    
                    NowDate.Checked = True
                    OtherDate.Checked = False
                    PostDateTxtBox.Enabled = False
                    imgPopup.Enabled = False
                    PostDateTxtBox.Attributes.Add("readonly", "true")
                    PostDateTxtBox.Text = Format(Now(), "dd-MMMM-yyyy")
    
    
                    queryString = "SELECT COUNT(*) FROM NewFromTargets WHERE (LoadedByUserName=@UN)"
                    Dim CheckSourceExist As New SqlCommand(queryString, connection)
                    CheckSourceExist.Parameters.Add("@UN", SqlDbType.NVarChar)
                    CheckSourceExist.Parameters("@UN").Value = UserName
                    Dim SourceExist As Integer = CheckSourceExist.ExecuteScalar()
    
                    If SourceExist = 0 Then
    
                        queryString = "SELECT Indx FROM Employees WHERE (UserName=@UN)"
                        Dim LoginUserIndxSelectCommand As New SqlCommand(queryString, connection)
                        LoginUserIndxSelectCommand.Parameters.Add("@UN", SqlDbType.NVarChar)
                        LoginUserIndxSelectCommand.Parameters("@UN").Value = UserName
                        Dim LoginUserIndx = LoginUserIndxSelectCommand.ExecuteScalar()
                        UserIndx = LoginUserIndx
    
                        'queryString = "INSERT INTO NewFromTargets(Indx,LoadedByUserName) SELECT UnitIndx,@UN FROM UnitsHeads WHERE (HeadIndx=@LoginUserIndx) AND (CAST (GETDATE() AS DateTime) BETWEEN Since AND Until)"
                        queryString = "INSERT INTO NewFromTargets(Indx,LoadedByUserName) " &
                                      "SELECT DISTINCT UnitsHeads.UnitIndx,@UN " &
                                      "FROM AdministrationUnits INNER JOIN UnitsHeads ON AdministrationUnits.Indx = UnitsHeads.UnitIndx " &
                                      "WHERE (HeadIndx=@LoginUserIndx) And (CAST(GETDATE() AS DateTime) BETWEEN UnitsHeads.Since And UnitsHeads.Until) And (CAST(GETDATE() AS DateTime) BETWEEN AdministrationUnits.FromDate And AdministrationUnits.ToDate)"
                        Dim LoginUserUnitSelectCommand As New SqlCommand(queryString, connection)
                        LoginUserUnitSelectCommand.Parameters.Add("@LoginUserIndx", SqlDbType.Int)
                        LoginUserUnitSelectCommand.Parameters("@LoginUserIndx").Value = UserIndx
                        LoginUserUnitSelectCommand.Parameters.Add("@UN", SqlDbType.NVarChar)
                        LoginUserUnitSelectCommand.Parameters("@UN").Value = UserName
                        LoginUserUnitSelectCommand.ExecuteNonQuery()
    
                        PlugTheFromTargetNames()
                    End If
    
                    SourceName.DataBind()
                    If Session("CollectSenderIndx") = 1 Then
                        If TDClass.IsAuthorized(SourceName.SelectedValue, UserName) = 1 Then
                            LoginingIndx = SourceName.SelectedValue
                            Session("LoginingIndx") = LoginingIndx
                            Session("CollectSenderIndx") = 0
                        End If
                    End If
    
    
                    If Session("NewPostExEntityBack") = 1 Then
    
    
                        'SHOW SOURCE NAME VALUE
                        queryString = "SELECT COUNT(*) FROM NewFromTargets WHERE (LoadedByUserName=@UN) AND (Indx=@Ix)"
                        Dim CheckExist As New SqlCommand(queryString, connection)
                        CheckExist.Parameters.Add("@Ix", SqlDbType.Int)
                        CheckExist.Parameters("@Ix").Value = Session("NewPostSourceValue")
                        CheckExist.Parameters.Add("@UN", SqlDbType.NVarChar)
                        CheckExist.Parameters("@UN").Value = Session("UserName")
                        If CheckExist.ExecuteScalar = 0 Then
                            'queryString = "INSERT INTO NewFromTargets(Indx,Name,LoadedByUserName) " & _
                            '                "SELECT Indx,Name,@UN FROM ExternalEntities WHERE (Indx=@Ix)"
                            queryString = "INSERT INTO NewFromTargets(Indx,Name,LoadedByUserName) " & _
                                          "VALUES (@Ix,@Name,@UN)"
                            Dim AddNewFromTarget As New SqlCommand(queryString, connection)
                            AddNewFromTarget.Parameters.Add("@Ix", SqlDbType.Int)
                            AddNewFromTarget.Parameters("@Ix").Value = Session("NewPostSourceValue")
                            AddNewFromTarget.Parameters.Add("@Name", SqlDbType.NVarChar)
                            AddNewFromTarget.Parameters("@Name").Value = Session("NewPostSourceName")
                            AddNewFromTarget.Parameters.Add("@UN", SqlDbType.NVarChar)
                            AddNewFromTarget.Parameters("@UN").Value = Session("UserName")
                            AddNewFromTarget.ExecuteNonQuery()
                        End If
    
                        SourceName.DataBind()
                        SourceName.SelectedValue = Session("NewPostSourceValue")
    
                        'SHOW TARGET NAME VALUE
                        queryString = "SELECT COUNT(*) FROM NewToTargets WHERE (Indx=@Ix) AND (LoadedByUserName=@UN)"
                        Dim CheckExist1 As New SqlCommand(queryString, connection)
                        CheckExist1.Parameters.Add("@Ix", SqlDbType.Int)
                        CheckExist1.Parameters("@Ix").Value = Session("NewPostTargetValue")
                        CheckExist1.Parameters.Add("@UN", SqlDbType.NVarChar)
                        CheckExist1.Parameters("@UN").Value = Session("UserName")
                        If CheckExist1.ExecuteScalar = 0 Then
                            queryString = "INSERT INTO NewToTargets(Indx,Name,LoadedByUserName) " & _
                                          "VALUES(@Ix,@Name,@UN)"
                            Dim AddNewToTarget As New SqlCommand(queryString, connection)
                            AddNewToTarget.Parameters.Add("@Ix", SqlDbType.Int)
                            AddNewToTarget.Parameters("@Ix").Value = Session("NewPostTargetValue")
                            AddNewToTarget.Parameters.Add("@Name", SqlDbType.NVarChar)
                            AddNewToTarget.Parameters("@Name").Value = Session("NewPostTargetName")
                            AddNewToTarget.Parameters.Add("@UN", SqlDbType.NVarChar)
                            AddNewToTarget.Parameters("@UN").Value = Session("UserName")
                            AddNewToTarget.ExecuteNonQuery()
                        End If
    
                        TargetName.DataBind()
                        TargetName.SelectedValue = Session("NewPostTargetValue")
    
                        queryString = "SELECT COUNT(*) FROM NewToTargetsA WHERE (Indx=@Ix) AND (LoadedByUserName=@UN)"
                        Dim CheckExist1A As New SqlCommand(queryString, connection)
                        CheckExist1A.Parameters.Add("@Ix", SqlDbType.Int)
                        CheckExist1A.Parameters("@Ix").Value = Session("NewPostTargetValue")
                        CheckExist1A.Parameters.Add("@UN", SqlDbType.NVarChar)
                        CheckExist1A.Parameters("@UN").Value = Session("UserName")
                        If CheckExist1A.ExecuteScalar = 0 Then
                            queryString = "INSERT INTO NewToTargetsA(Indx,Name,LoadedByUserName) " & _
                                          "VALUES(@Ix,@Name,@UN)"
                            Dim AddNewToTarget As New SqlCommand(queryString, connection)
                            AddNewToTarget.Parameters.Add("@Ix", SqlDbType.Int)
                            AddNewToTarget.Parameters("@Ix").Value = Session("NewPostTargetValue")
                            AddNewToTarget.Parameters.Add("@Name", SqlDbType.NVarChar)
                            AddNewToTarget.Parameters("@Name").Value = Session("NewPostTargetName")
                            AddNewToTarget.Parameters.Add("@UN", SqlDbType.NVarChar)
                            AddNewToTarget.Parameters("@UN").Value = Session("UserName")
                            AddNewToTarget.ExecuteNonQuery()
                        End If
    
                        If Session("NewPostTrigger") = "source" Then
                            If CheckIfExternal(Session("NewPostSourceValue")) = 1 Then
                                queryString = "SELECT COUNT(*) FROM NewToTargets WHERE (Indx=@Ix) AND (LoadedByUserName=@UN)"
                                Dim CheckExist2 As New SqlCommand(queryString, connection)
                                CheckExist2.Parameters.Add("@Ix", SqlDbType.Int)
                                CheckExist2.Parameters("@Ix").Value = Session("OldPostSourceValue")
                                CheckExist2.Parameters.Add("@UN", SqlDbType.NVarChar)
                                CheckExist2.Parameters("@UN").Value = Session("UserName")
                                If CheckExist2.ExecuteScalar = 0 Then
                                    queryString = "INSERT INTO NewToTargets(Indx,LoadedByUserName) " & _
                                                  "VALUES(@Ix,@UN)"
                                    Dim AddNewToTargetN As New SqlCommand(queryString, connection)
                                    AddNewToTargetN.Parameters.Add("@Ix", SqlDbType.Int)
                                    AddNewToTargetN.Parameters("@Ix").Value = Session("OldPostSourceValue")
                                    AddNewToTargetN.Parameters.Add("@UN", SqlDbType.NVarChar)
                                    AddNewToTargetN.Parameters("@UN").Value = Session("UserName")
                                    AddNewToTargetN.ExecuteNonQuery()
    
                                    PlugTheToTargetNames()
    
                                End If
    
                                TargetName.DataBind()
                                TargetName.SelectedValue = Session("NewPostTargetValue")
                            End If
                        End If
    
    
    
                        If Session("NewPostAloneCB") = "true" Then
                            AloneCB.Checked = True
                            TargetName.Enabled = True
                            PickToExEntity.Enabled = True
                            PickToExEntity.BackColor = EnabledColor
                            MultiCB.Checked = False
                            OpenMultiTargets.Enabled = False
                            OpenMultiTargets.BackColor = DisabledColor
                        Else
                            AloneCB.Checked = False
                            PickToExEntity.Enabled = False
                            PickToExEntity.BackColor = DisabledColor
                            MultiCB.Checked = True
                            OpenMultiTargets.Enabled = True
                            OpenMultiTargets.BackColor = EnabledColor
                        End If
    
                        If Session("NewPostMultiCB") = "true" Then
                            MultiCB.Checked = True
                            AloneCB.Checked = False
                            PickToExEntity.Enabled = False
                            PickToExEntity.BackColor = DisabledColor
                            MultiCB.Checked = True
                            OpenMultiTargets.Enabled = True
                            OpenMultiTargets.BackColor = EnabledColor
                        Else
                            MultiCB.Checked = False
                            AloneCB.Checked = True
                            TargetName.Enabled = True
                            PickToExEntity.Enabled = True
                            PickToExEntity.BackColor = EnabledColor
                            MultiCB.Checked = False
                            OpenMultiTargets.Enabled = False
                            OpenMultiTargets.BackColor = DisabledColor
                        End If
    
                        If Session("PostDateNowDate") = "false" Then
                            NowDate.Checked = False
                            OtherDate.Checked = True
                            PostDateTxtBox.Enabled = True
                            imgPopup.Enabled = True
                        Else
                            NowDate.Checked = True
                            OtherDate.Checked = False
                            PostDateTxtBox.Enabled = False
                            imgPopup.Enabled = False
                        End If
    
                        If DateDiff("s", "#12:00:00 AM#", Session("NewPostDateVal")) <> 0 Then
                            PostDateTxtBox.Text = Session("NewPostDateVal")
                        End If
    
                        If CheckIfExternal(SourceName.SelectedValue) = 0 Then
                            StorageUnit = SourceName.SelectedValue
                            LetterIDPublic = TDClass.GenerateNewID(StorageUnit)
                            LetterIDTxtBox.Text = LetterIDPublic
    
                        Else
                            If CheckIfExternal(TargetName.SelectedValue) = 0 Then
                                StorageUnit = TargetName.SelectedValue
                                LetterIDPublic = TDClass.GenerateNewID(StorageUnit)
                                LetterIDTxtBox.Text = LetterIDPublic
                            End If
    
                        End If
    
                        If CheckIfExternal(SourceName.SelectedValue) = 1 And CheckIfExternal(TargetName.SelectedValue) = 1 Then
                            LetterIDTxtBox.Text = LetterIDPublic
                        End If
    
                        FollowUpID.Text = Session("NewPostFollowUpID")
                        SubjectTxtBox.Text = Session("NewPostSubject")
                        CommentsTxtBox.Text = Session("NewPostComments")
                        PostTypeDDL.DataBind()
                        PostTypeDDL.SelectedValue = Session("NewPostTypeDDLValue")
                        If Session("NewPostTypeDDLValue") <> "" Then
                            If Session("NewPostTypeDDLValue") = "طلب" Then
                                RAPTxtBox.Enabled = True
                                RAPTxtBox.Text = Session("NewPostRAPTxtBox")
                            ElseIf Session("NewPostTypeDDLValue") = "للعلم" Then
                                RAPTxtBox.Text = ""
                                RAPTxtBox.Enabled = False
                            End If
                        End If
    
                        If Session("NewPostIsTopSecret") = "true" Then
                            IsTopSecret.Checked = True
                        ElseIf Session("NewPostIsTopSecret") = "false" Then
                            IsTopSecret.Checked = False
                        End If
    
                        ImportanceDD.DataBind()
                        ImportanceDD.SelectedValue = Session("NewPostImportanceValue")
                        AttachmentTypeError = 1
    
                        'Fix the target name to be as the logging user when the sender is external
                        If TDClass.CheckIfExternal(SourceName.SelectedValue) = 1 Then
                            'TargetName.SelectedValue = LoginingIndx
                            If TDClass.IsAdministrator(UserName) = 1 Then
                                TargetName.SelectedValue = 90001
                            Else
                                TargetName.SelectedValue = LoginingIndx
                            End If
    
                            StorageUnit = TargetName.SelectedValue
                            LetterIDPublic = TDClass.GenerateNewID(StorageUnit)
                            LetterIDTxtBox.Text = LetterIDPublic
                            'TargetName.Enabled = False
                            AloneCB.Checked = True
                            AloneCB.Enabled = False
                            MultiCB.Checked = False
                            MultiCB.Enabled = False
                            OpenMultiTargets.Enabled = False
                            OpenMultiTargets.BackColor = DisabledColor
                            PickToExEntity.Enabled = False
                            PickToExEntity.BackColor = DisabledColor
                        Else
                            StorageUnit = SourceName.SelectedValue
                            LetterIDPublic = TDClass.GenerateNewID(StorageUnit)
                            LetterIDTxtBox.Text = LetterIDPublic
                            TargetName.Enabled = True
                            AloneCB.Checked = True
                            AloneCB.Enabled = True
                            MultiCB.Checked = False
                            MultiCB.Enabled = True
                            OpenMultiTargets.Enabled = False
                            OpenMultiTargets.BackColor = DisabledColor
                            PickToExEntity.Enabled = True
                            PickToExEntity.BackColor = EnabledColor
                        End If
    
                        Session("NewPostExEntityBack") = 0
                        GoTo ResumtionLabel
    
                    End If
    
    
                    If Session("DraftNewPost") = 1 Then
    
                        'SHOW SOURCE NAME VALUE
                        queryString = "SELECT COUNT(*) FROM NewFromTargets WHERE (LoadedByUserName=@UN) AND (Indx=@Ix)"
                        Dim CheckExist As New SqlCommand(queryString, connection)
                        CheckExist.Parameters.Add("@Ix", SqlDbType.Int)
                        CheckExist.Parameters("@Ix").Value = Session("DraftNewPostSource")
                        CheckExist.Parameters.Add("@UN", SqlDbType.NVarChar)
                        CheckExist.Parameters("@UN").Value = Session("UserName")
                        If CheckExist.ExecuteScalar = 0 Then
                            queryString = "INSERT INTO NewFromTargets(Indx,Name,LoadedByUserName) " & _
                                          "VALUES (@Ix,@Name,@UN)"
                            Dim AddNewFromTarget As New SqlCommand(queryString, connection)
                            AddNewFromTarget.Parameters.Add("@Ix", SqlDbType.Int)
                            AddNewFromTarget.Parameters("@Ix").Value = Session("DraftNewPostSource")
                            AddNewFromTarget.Parameters.Add("@Name", SqlDbType.NVarChar)
                            AddNewFromTarget.Parameters("@Name").Value = Session("DraftNewPostSourceName")
                            AddNewFromTarget.Parameters.Add("@UN", SqlDbType.NVarChar)
                            AddNewFromTarget.Parameters("@UN").Value = Session("UserName")
                            AddNewFromTarget.ExecuteNonQuery()
                        End If
    
                        SourceName.DataBind()
                        SourceName.SelectedValue = Session("DraftNewPostSource")
    
                        'SHOW TARGET NAME VALUE
                        queryString = "SELECT COUNT(*) FROM NewToTargets WHERE (Indx=@Ix) AND (LoadedByUserName=@UN)"
                        Dim CheckExist1 As New SqlCommand(queryString, connection)
                        CheckExist1.Parameters.Add("@Ix", SqlDbType.Int)
                        CheckExist1.Parameters("@Ix").Value = Session("DraftNewPostTarget")
                        CheckExist1.Parameters.Add("@UN", SqlDbType.NVarChar)
                        CheckExist1.Parameters("@UN").Value = Session("UserName")
                        If CheckExist1.ExecuteScalar = 0 Then
                            queryString = "INSERT INTO NewToTargets(Indx,Name,LoadedByUserName) " & _
                                          "VALUES(@Ix,@Name,@UN)"
                            Dim AddNewToTarget As New SqlCommand(queryString, connection)
                            AddNewToTarget.Parameters.Add("@Ix", SqlDbType.Int)
                            AddNewToTarget.Parameters("@Ix").Value = Session("DraftNewPostTarget")
                            AddNewToTarget.Parameters.Add("@Name", SqlDbType.NVarChar)
                            AddNewToTarget.Parameters("@Name").Value = Session("DraftNewPostTargetName")
                            AddNewToTarget.Parameters.Add("@UN", SqlDbType.NVarChar)
                            AddNewToTarget.Parameters("@UN").Value = Session("UserName")
                            AddNewToTarget.ExecuteNonQuery()
                        End If
    
                        TargetName.DataBind()
                        TargetName.SelectedValue = Session("DraftNewPostTarget")
    
                        LetterIDPublic = Session("DraftNewPostLetterID")
                        LetterIDTxtBox.Text = LetterIDPublic
    
                        FollowUpID.Text = Session("DraftNewPostFollowUpID")
    
                        SubjectTxtBox.Text = Session("DraftNewPostSubject")
                        CommentsTxtBox.Text = Session("DraftNewPostComments")
                        If Session("DraftNewPostAloneCB") = "true" Then
                            AloneCB.Checked = True
                            TargetName.Enabled = True
                            PickToExEntity.Enabled = True
                            PickToExEntity.BackColor = EnabledColor
                            MultiCB.Checked = False
                            OpenMultiTargets.Enabled = False
                            OpenMultiTargets.BackColor = DisabledColor
                        Else
                            AloneCB.Checked = False
                            PickToExEntity.Enabled = False
                            PickToExEntity.BackColor = DisabledColor
                            MultiCB.Checked = True
                            OpenMultiTargets.Enabled = True
                            OpenMultiTargets.BackColor = EnabledColor
                        End If
    
                        If Session("DraftNewPostMultiCB") = "true" Then
                            MultiCB.Checked = True
                            AloneCB.Checked = False
                            PickToExEntity.Enabled = False
                            PickToExEntity.BackColor = DisabledColor
                            MultiCB.Checked = True
                            OpenMultiTargets.Enabled = True
                            OpenMultiTargets.BackColor = EnabledColor
                        Else
                            MultiCB.Checked = False
                            AloneCB.Checked = True
                            TargetName.Enabled = True
                            PickToExEntity.Enabled = True
                            PickToExEntity.BackColor = EnabledColor
                            MultiCB.Checked = False
                            OpenMultiTargets.Enabled = False
                            OpenMultiTargets.BackColor = DisabledColor
                        End If
    
                        If Session("DraftNewPostDateNowDate") = "false" Then
                            NowDate.Checked = False
                            OtherDate.Checked = True
                            PostDateTxtBox.Enabled = True
                            imgPopup.Enabled = True
                        Else
                            NowDate.Checked = True
                            OtherDate.Checked = False
                            PostDateTxtBox.Enabled = False
                            imgPopup.Enabled = False
                        End If
    
    
                        If DateDiff("s", "#12:00:00 AM#", Session("DraftNewPostDate")) <> 0 Then
                            Dim ReturnedPostDate As String
                            ReturnedPostDate = TDClass.FormatDraftPostdate(Session("DraftNewPostDate"))
                            PostDateTxtBox.Text = ReturnedPostDate
                        End If
    
                        If Session("DraftNewPostTypeDDLValue") <> "" Then
                            If Session("DraftNewPostTypeDDLValue") = "طلب" Then
                                RAPTxtBox.Enabled = True
                                RAPTxtBox.Text = Session("DraftNewPostRAPTxtBox")
                            ElseIf Session("DraftNewPostTypeDDLValue") = "للعلم" Then
                                RAPTxtBox.Text = ""
                                RAPTxtBox.Enabled = False
                            End If
                            PostTypeDDL.SelectedValue = Session("DraftNewPostTypeDDLValue")
                        End If
    
                        If Session("DraftNewPostIsTopSecret") = "true" Then
                            IsTopSecret.Checked = True
                        ElseIf Session("DraftNewPostIsTopSecret") = "false" Then
                            IsTopSecret.Checked = False
                        End If
    
                        ImportanceDD.DataBind()
                        ImportanceDD.SelectedValue = Session("DraftNewPostImportanceValue")
    
                        SourceName.Enabled = False
                        TargetName.Enabled = False
                        PickFromExEntity.Enabled = False
                        PickFromExEntity.BackColor = DisabledColor
                        PickToExEntity.Enabled = False
                        PickToExEntity.BackColor = DisabledColor
    
                        AloneCB.Enabled = False
                        MultiCB.Enabled = False
                        OpenMultiTargets.Enabled = False
                        OpenMultiTargets.BackColor = DisabledColor
    
                        If Session("DraftNewPostMultiCB") = "true" Then
                            MultiCB.Enabled = True
                            MultiCB.Checked = True
                            AloneCB.Checked = False
                            OpenMultiTargets.Enabled = True
                            OpenMultiTargets.BackColor = EnabledColor
                            MultiCBUncheckable = 1
                        End If
    
                        Session("DraftNewPost") = 0
    
                        GoTo ResumtionLabel
    
                    End If
    
    
                    If Session("DraftChangeLetterIDBack") = 1 Then
    
                        SourceName.DataBind()
                        SourceName.SelectedValue = Session("DraftChangeLetterIDSource")
    
                        TargetName.DataBind()
                        TargetName.SelectedValue = Session("DraftChangeLetterIDTarget")
    
                        LetterIDPublic = Session("DraftChangeLetterIDValue")
                        LetterIDTxtBox.Text = LetterIDPublic
    
                        FollowUpID.Text = Session("DraftChangeFollowUpIDValue")
    
                        SubjectTxtBox.Text = Session("DraftChangeLetterIDSubject")
                        CommentsTxtBox.Text = Session("DraftChangeLetterIDComments")
    
                        If Session("DraftChangeLetterIDAloneCB") = "true" Then
                            AloneCB.Checked = True
                            TargetName.Enabled = True
                            PickToExEntity.Enabled = True
                            PickToExEntity.BackColor = EnabledColor
                            MultiCB.Checked = False
                            OpenMultiTargets.Enabled = False
                            OpenMultiTargets.BackColor = DisabledColor
                        Else
                            AloneCB.Checked = False
                            PickToExEntity.Enabled = False
                            PickToExEntity.BackColor = DisabledColor
                            MultiCB.Checked = True
                            OpenMultiTargets.Enabled = True
                            OpenMultiTargets.BackColor = EnabledColor
                        End If
    
                        If Session("DraftChangeLetterIDMultiCB") = "true" Then
                            MultiCB.Checked = True
                            AloneCB.Checked = False
                            PickToExEntity.Enabled = False
                            PickToExEntity.BackColor = DisabledColor
                            MultiCB.Checked = True
                            OpenMultiTargets.Enabled = True
                            OpenMultiTargets.BackColor = EnabledColor
                        Else
                            MultiCB.Checked = False
                            AloneCB.Checked = True
                            TargetName.Enabled = True
                            PickToExEntity.Enabled = True
                            PickToExEntity.BackColor = EnabledColor
                            MultiCB.Checked = False
                            OpenMultiTargets.Enabled = False
                            OpenMultiTargets.BackColor = DisabledColor
                        End If
    
                        If Session("DraftChangeLetterIDNowDate") = "false" Then
                            NowDate.Checked = False
                            OtherDate.Checked = True
                        Else
                            NowDate.Checked = True
                            OtherDate.Checked = False
                        End If
    
    
                        If DateDiff("s", "#12:00:00 AM#", Session("DraftChangeLetterIDDateVal")) <> 0 Then
                            Dim ReturnedPostDate As String
                            ReturnedPostDate = TDClass.FormatDraftPostdate(Session("DraftChangeLetterIDDateVal"))
                            PostDateTxtBox.Text = ReturnedPostDate
                        End If
    
    
                        If Session("DraftChangeLetterIDTypeDDLValue") <> "" Then
                            If Session("DraftChangeLetterIDTypeDDLValue") = "طلب" Then
                                RAPTxtBox.Enabled = True
                                RAPTxtBox.Text = Session("DraftChangeLetterIDRAP")
                            ElseIf Session("DraftChangeLetterIDTypeDDLValue") = "للعلم" Then
                                RAPTxtBox.Text = ""
                                RAPTxtBox.Enabled = False
                            End If
                            PostTypeDDL.SelectedValue = Session("DraftChangeLetterIDTypeDDLValue")
                        End If
    
                        If Session("DraftChangeLetterIDIsTopSecret") = "true" Then
                            IsTopSecret.Checked = True
                        ElseIf Session("DraftChangeLetterIDIsTopSecret") = "false" Then
                            IsTopSecret.Checked = False
                        End If
    
                        ImportanceDD.DataBind()
                        ImportanceDD.SelectedValue = Session("DraftChangeLetterIDImportanceValue")
    
                        If Session("DraftNewPostLetterID") <> "" Then
                            SourceName.Enabled = False
                            TargetName.Enabled = False
                            PickFromExEntity.Enabled = False
                            PickFromExEntity.BackColor = DisabledColor
                            PickToExEntity.Enabled = False
                            PickToExEntity.BackColor = DisabledColor
                        End If
    
                        Session("DraftChangeLetterIDBack") = 0
                        GoTo ResumtionLabel
    
                    End If
    
                    FollowUpID.Text = TDClass.GetFollowUpID()
    
                    AloneCB.Checked = True
                    MultiCB.Checked = False
                    TargetName.Enabled = True
                    OpenMultiTargets.Enabled = False
                    OpenMultiTargets.BackColor = DisabledColor
    
                    UserName = Session("UserName")
    
                    Dim importance As String = "Normal"
                    LetterIDTxtBox.Text = ""
    
                    PostTypeDDL.Text = "طلب"
                    RAPTxtBox.Text = 7
    
                    ClearNewPostFromTargetUnits(UserName)
                    ClearFromToTargets(UserName)
                    ClearCCToTargets(UserName)
                    PrepareTags(UserName)
                    PushtheNewFromUnits(UserName)
                    PlugTheFromTargetNames()
                    SourceName.DataBind()
    
                    BuildTheNewToTargets(UserName)
                    TargetName.DataBind()
                    SetSourceNameInitialValue()
                    SetTargetNameInitialValue(UserName)
                    RemoveSourceNameSelectedIndxFromTargetName()
                    PreparePrivateAllUsers(UserName)
                    ClearIncomingInfo(UserName)
    
    
                    NowDate.Checked = True
                    OtherDate.Checked = False
    
                    Session("DraftNewPostLetterID") = ""
                    Session("DraftNewPostFollowUpID") = ""
    
                End Using
    ResumtionLabel:
            End If
    
        End Sub
    
        Protected Sub SourceName_ServerValidate(source As Object, args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles BothIdenticalValidator.ServerValidate
            If SourceName.SelectedValue = TargetName.SelectedValue And AloneCB.Checked = True Then
                args.IsValid = False
            End If
    
        End Sub
    
        Public Shared Function CheckIfExternal(ByVal PassedIndx As Integer) As Integer
    
            Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
            Using connection As New SqlConnection(conString)
    
                connection.Open()
    
                queryString = "SELECT COUNT(*) FROM ExternalEntities WHERE (Indx = @Ix)"
                Dim IndxCounter As New SqlCommand(queryString, connection)
                IndxCounter.Parameters.Add("@Ix", SqlDbType.Int)
                IndxCounter.Parameters("@Ix").Value = PassedIndx
                CheckIfExternal = IndxCounter.ExecuteScalar()
                If CheckIfExternal >= 1 Then
                    CheckIfExternal = 1
                Else
                    CheckIfExternal = 0
                End If
    
            End Using
    
        End Function
    
        Protected Sub PostNewLetter_Click(sender As Object, e As EventArgs) Handles PostNewLetter.Click
    
            AttachmentRequiredFile.Enabled = True
            'AttachmentFileType.Enabled = True
            'AttachmentFilesCount.Enabled = True
    
            Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
            Using connection As New SqlConnection(conString)
    
                connection.Open()
    
                PerformValidation = 1
    
    
                If Page.IsValid = True Then
    
                    If CheckIfExternal(SourceName.SelectedValue) = 0 Then
                        'Check DataEntryRight for session("username") on the SourceName Unit
                        UserUnitIndx = SourceName.SelectedValue
                    ElseIf CheckIfExternal(TargetName.SelectedValue) = 0 Then
                        'Check DataEntryRight for session("username") on the TargetName Unit
                        'If DataEntryRight=0 then Redirect to ("~\NewLetterNotSent.aspx")
                        UserUnitIndx = TargetName.SelectedValue
                    End If
    
                    Dim Existing As Integer
                    queryString = "SELECT COUNT(*) FROM Postings WHERE (LetterID=@LID) OR (RefNo=@LID)"
                    Dim CheckExistence As New SqlCommand(queryString, connection)
                    CheckExistence.Parameters.Add("@LID", SqlDbType.NVarChar)
                    CheckExistence.Parameters("@LID").Value = LetterIDTxtBox.Text
                    Existing = CheckExistence.ExecuteScalar
    
                    If Existing > 0 Then
                        Response.Redirect("~\NewPosting\NewLetterExisting.aspx")
                    End If
    
                    If AloneCB.Checked = True And MultiCB.Checked = False Then
    
                        Dim TheSelectedFileSourcePath As String = AttachmentsSelecter.FileName
                        Dim DotPos As Integer = InStr(TheSelectedFileSourcePath, ".")
                        Dim FileExtension As String = TheSelectedFileSourcePath.Substring(DotPos, Len(TheSelectedFileSourcePath) - DotPos)
                        Dim LocalPath As String
    
                        LocalPath = "~\PdfDirectory\"
                        'Dim FileToDelete As String = LocalPath & LetterIDPublic & ".doc"
                        'If System.IO.File.Exists(FileToDelete) = True Then
                        '    System.IO.File.Delete(FileToDelete)
                        'End If
    
                        'FileToDelete = LocalPath & LetterIDPublic & ".docx"
                        'If System.IO.File.Exists(FileToDelete) = True Then
                        '    System.IO.File.Delete(FileToDelete)
                        'End If
    
                        'FileToDelete = LocalPath & LetterIDPublic & ".pdf"
                        'If System.IO.File.Exists(FileToDelete) = True Then
                        '    System.IO.File.Delete(FileToDelete)
                        'End If
    
                        'FileToDelete = LocalPath & LetterIDPublic & ".jpg"
                        'If System.IO.File.Exists(FileToDelete) = True Then
                        '    System.IO.File.Delete(FileToDelete)
                        'End If
    
                        'FileToDelete = LocalPath & LetterIDPublic & ".TIF"
                        'If System.IO.File.Exists(FileToDelete) = True Then
                        '    System.IO.File.Delete(FileToDelete)
                        'End If
    
    
                        'Dim ServerPath As String = TDClass.GetTheServerStoragePath(StorageUnit)
                        'TheAttachedFileServerPath = ServerPath & LetterIDPublic & "." & FileExtension
                        'AttachmentsSelecter.SaveAs(TheAttachedFileServerPath
    
                        UploadAttachments(StorageUnit)
    
                        'queryString = "INSERT INTO NewPosting (LetterID, Source, Target, PostTime, PostType, Importance, RequiredAnsPeriod, Subject, Comments, LoadedByUserName, LoggingUserName,TopPrivate) VALUES (@LID,@SRC,@TGT,@PTime,@PType,@Imp,@RAP,@Subj,@Cmts,@UN,@UN,@Pvt)"
                        queryString = "INSERT INTO Postings (LetterID, Source, Target, PostTime, PostType, Importance, RequiredAnsPeriod, Subject, Comments,  LoggingUserName,TopPrivate) VALUES (@LID,@SRC,@TGT,@PTime,@PType,@Imp,@RAP,@Subj,@Cmts,@UN,@Pvt)"
                        Dim InsertNewPost As New SqlCommand(queryString, connection)
                        InsertNewPost.Parameters.Add("@LID", SqlDbType.NVarChar)
                        InsertNewPost.Parameters("@LID").Value = Trim(LetterIDTxtBox.Text)
                        InsertNewPost.Parameters.Add("@SRC", SqlDbType.Int)
                        InsertNewPost.Parameters("@SRC").Value = SourceName.SelectedValue
                        InsertNewPost.Parameters.Add("@TGT", SqlDbType.Int)
                        InsertNewPost.Parameters("@TGT").Value = TargetName.SelectedValue
                        InsertNewPost.Parameters.Add("@PTime", SqlDbType.DateTime)
                        If NowDate.Checked = True Then
                            InsertNewPost.Parameters("@PTime").Value = Now()
                        ElseIf OtherDate.Checked = True Then
                            InsertNewPost.Parameters("@PTime").Value = PostDate
                        End If
    
                        InsertNewPost.Parameters.Add("@Imp", SqlDbType.NVarChar)
                        InsertNewPost.Parameters("@Imp").Value = ImportanceDD.SelectedValue
                        InsertNewPost.Parameters.Add("@RAP", SqlDbType.Int)
                        InsertNewPost.Parameters.Add("@PType", SqlDbType.NVarChar)
                        If PostTypeDDL.Text = "للعلم" Then
                            InsertNewPost.Parameters("@RAP").Value = 0
                            InsertNewPost.Parameters("@PType").Value = "للعلم"
                        Else
                            InsertNewPost.Parameters("@RAP").Value = CInt(RAPTxtBox.Text)
                            InsertNewPost.Parameters("@PType").Value = "طلب"
                        End If
                        InsertNewPost.Parameters.Add("@Subj", SqlDbType.NVarChar)
                        InsertNewPost.Parameters("@Subj").Value = Trim(SubjectTxtBox.Text)
                        InsertNewPost.Parameters.Add("@Cmts", SqlDbType.NVarChar)
                        InsertNewPost.Parameters("@Cmts").Value = Trim(CommentsTxtBox.Text)
                        InsertNewPost.Parameters.Add("@UN", SqlDbType.NVarChar)
                        InsertNewPost.Parameters("@UN").Value = UserName
                        If IsTopSecret.Checked = True Then
                            InsertNewPost.Parameters.Add("@Pvt", SqlDbType.Int)
                            InsertNewPost.Parameters("@Pvt").Value = 1
                        Else
                            InsertNewPost.Parameters.Add("@Pvt", SqlDbType.Int)
                            InsertNewPost.Parameters("@Pvt").Value = 0
                        End If
                        InsertNewPost.ExecuteNonQuery()
    
                        'queryString = "UPDATE NewPosting SET Importance=@ImportNew WHERE (Importance=@ImportCurrent) AND (LetterID=@LID)"
                        queryString = "UPDATE Postings SET Importance=@ImportNew WHERE (Importance=@ImportCurrent) AND (LetterID=@LID)"
                        Dim UpdateHighImportanceValue As New SqlCommand(queryString, connection)
                        UpdateHighImportanceValue.Parameters.Add("@ImportNew", SqlDbType.NVarChar)
                        UpdateHighImportanceValue.Parameters.Add("@ImportCurrent", SqlDbType.NVarChar)
                        UpdateHighImportanceValue.Parameters.Add("@LID", SqlDbType.NVarChar)
                        UpdateHighImportanceValue.Parameters("@ImportNew").Value = "High"
                        UpdateHighImportanceValue.Parameters("@ImportCurrent").Value = "هام"
                        UpdateHighImportanceValue.Parameters("@LID").Value = LetterIDTxtBox.Text
                        UpdateHighImportanceValue.ExecuteNonQuery()
    
                        'queryString = "UPDATE NewPosting SET Importance=@ImportNew WHERE (Importance=@ImportCurrent) AND (LetterID=@LID)"
                        queryString = "UPDATE Postings SET Importance=@ImportNew WHERE (Importance=@ImportCurrent) AND (LetterID=@LID)"
                        Dim UpdateNormalImportanceValue As New SqlCommand(queryString, connection)
                        UpdateNormalImportanceValue.Parameters.Add("@ImportNew", SqlDbType.NVarChar)
                        UpdateNormalImportanceValue.Parameters.Add("@ImportCurrent", SqlDbType.NVarChar)
                        UpdateNormalImportanceValue.Parameters.Add("@LID", SqlDbType.NVarChar)
                        UpdateNormalImportanceValue.Parameters("@ImportNew").Value = "Normal"
                        UpdateNormalImportanceValue.Parameters("@ImportCurrent").Value = "اعتيادي"
                        UpdateNormalImportanceValue.Parameters("@LID").Value = LetterIDTxtBox.Text
                        UpdateNormalImportanceValue.ExecuteNonQuery()
    
                        'queryString = "UPDATE NewPosting SET LoggingTime = @TS WHERE (LetterID = @LID)"
                        queryString = "UPDATE Postings SET LoggingTime = @TS WHERE (LetterID = @LID)"
                        Dim TimeStampQS As New SqlCommand(queryString, connection)
                        TimeStampQS.Parameters.Add("@TS", SqlDbType.DateTime)
                        TimeStampQS.Parameters("@TS").Value = Now()
                        TimeStampQS.Parameters.Add("@LID", SqlDbType.NVarChar)
                        TimeStampQS.Parameters("@LID").Value = LetterIDTxtBox.Text
                        TimeStampQS.ExecuteNonQuery()
    
                        If TDClass.CheckIfExternal(SourceName.SelectedValue) = 1 Then
    
                            queryString = "SELECT COUNT(*) FROM IncomingLetterInfo WHERE (LoadedByUserIndx=@Ix)"
                            Dim CountIncomingLetterInfoRows As New SqlCommand(queryString, connection)
                            CountIncomingLetterInfoRows.Parameters.Add("@Ix", SqlDbType.Int)
                            CountIncomingLetterInfoRows.Parameters("@Ix").Value = TDClass.GetLoggingUserIndxValue(UserName)
                            Dim IncomingLetterInfoRows As Integer = CountIncomingLetterInfoRows.ExecuteScalar()
    
                            If IncomingLetterInfoRows > 0 Then
    
                                queryString = "SELECT IncomeRefNo,IncomePostDate FROM IncomingLetterInfo WHERE (LoadedByUserIndx=@Ix)"
                                Dim GetIncomingInfo As New SqlCommand(queryString, connection)
                                GetIncomingInfo.Parameters.Add("@Ix", SqlDbType.Int)
                                GetIncomingInfo.Parameters("@Ix").Value = TDClass.GetLoggingUserIndxValue(UserName)
                                Dim IncomingInfoReader As SqlDataReader = GetIncomingInfo.ExecuteReader
                                
    
                                If IncomingInfoReader.HasRows Then
                                    IncomingInfoReader.Read()
                                    InRefNo = IncomingInfoReader(0)
                                    InPostDate = IncomingInfoReader(1)
                                    IncomingInfoReader.Close()
                                End If
    
                                If InRefNo <> "" Then
                                    queryString = "UPDATE Postings SET IncomeRefNo=@InRNo WHERE (LetterID=@LID)"
                                    Dim PlugIncomingLetterInfo As New SqlCommand(queryString, connection)
                                    PlugIncomingLetterInfo.Parameters.Add("@InRNo", SqlDbType.NVarChar)
                                    PlugIncomingLetterInfo.Parameters.Add("@LID", SqlDbType.NVarChar)
                                    PlugIncomingLetterInfo.Parameters("@InRNo").Value = InRefNo
                                    PlugIncomingLetterInfo.Parameters("@LID").Value = LetterIDTxtBox.Text
                                    PlugIncomingLetterInfo.ExecuteNonQuery()
                                End If
    
                                If DateDiff(DateInterval.Day, InPostDate, Date.Parse("01-01-1900")) <> 0 Then
                                    queryString = "UPDATE Postings SET IncomePostDate=@InPD WHERE (LetterID=@LID)"
                                    Dim PlugIncomingLetterInfo As New SqlCommand(queryString, connection)
                                    PlugIncomingLetterInfo.Parameters.Add("@InPD", SqlDbType.Date)
                                    PlugIncomingLetterInfo.Parameters.Add("@LID", SqlDbType.NVarChar)
                                    PlugIncomingLetterInfo.Parameters("@InPD").Value = InPostDate
                                    PlugIncomingLetterInfo.Parameters("@LID").Value = LetterIDTxtBox.Text
                                    PlugIncomingLetterInfo.ExecuteNonQuery()
                                End If
    
                            End If
    
                        End If
    
                    ElseIf AloneCB.Checked = False And MultiCB.Checked = True Then
                        SendLettertoMultiTargets()
                    End If
    
    
                    'Insert the Initial PostingsStatus Record
                    If PostTypeDDL.Text = "طلب" Then
    
                        Dim InitRefNo As String
                        Dim InitPostTime As DateTime
                        Dim InitRAP As Integer
    
                        InitRefNo = Trim(LetterIDTxtBox.Text)
                        If NowDate.Checked = True Then
                            InitPostTime = Now()
                        ElseIf OtherDate.Checked = True Then
                            InitPostTime = PostDate
                        End If
                        InitRAP = CInt(RAPTxtBox.Text)
                        TDClass.InitiateStatusReecord(InitRefNo, InitPostTime, InitRAP)
    
                    End If
    
    
                    ComposeNewMessageCopies()
    
                    queryString = "UPDATE Postings SET ByTargets=@ByTgt WHERE (LetterID=@LID) OR (RefNo=@LID)"
                    Dim PlugByTargetsValues As New SqlCommand(queryString, connection)
                    PlugByTargetsValues.Parameters.Add("@ByTgt", SqlDbType.NVarChar)
                    If AloneCB.Checked = True Then
                        PlugByTargetsValues.Parameters("@ByTgt").Value = "One"
                    ElseIf MultiCB.Checked = True Then
                        PlugByTargetsValues.Parameters("@ByTgt").Value = "Multi"
                    End If
                    PlugByTargetsValues.Parameters.Add("@LID", SqlDbType.NVarChar)
                    PlugByTargetsValues.Parameters("@LID").Value = LetterIDTxtBox.Text
                    PlugByTargetsValues.ExecuteNonQuery()
    
                    StorePostingTags()
                    If IsTopSecret.Checked = True Then
                        StorePrivatePostingsRecords(UserName)
                    End If
    
                    ClearIncomingInfo(UserName)
                    GridView1.DataBind()
    
                    ClearNewPostingLetter()
    
                    RemoveDeletedLetterRecordsFromDraftTables(LetterIDTxtBox.Text)
    
    
                    Response.Redirect("~\NewPosting\NewLetterMessageSent.aspx")
    
                End If
            End Using
        End Sub
    
        Protected Sub AttachmentValidator1(source As Object, args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles AttachmentFileType.ServerValidate
    
            If PerformValidation = 0 Then GoTo finishLoop
    
            If AttachmentsSelecter.HasFile = False Then
                GoTo finishLoop
            End If
    
            For Each postedFile As HttpPostedFile In AttachmentsSelecter.PostedFiles
                Dim fileName As String = Path.GetFileName(postedFile.FileName)
    
                Dim TheSelectedFileSourcePath As String = postedFile.FileName
                Dim DotPos As Integer = InStr(TheSelectedFileSourcePath, ".")
                Dim FileExtension As String = TheSelectedFileSourcePath.Substring(DotPos, Len(TheSelectedFileSourcePath) - DotPos)
                If FileExtension <> "pdf" And FileExtension <> "doc" And FileExtension <> "docx" And FileExtension <> "TIF" And FileExtension <> "jpg" And FileExtension <> "PPT" And FileExtension <> "PPTX" And FileExtension <> "TXT" Then
                    args.IsValid = False
                    GoTo finishLoop
                End If
    
            Next
    finishLoop:
    
        End Sub
    
        Public Shared Sub GenerateTheToTargetsSameLevel(ByVal Indx As Integer, UserName As String)
    
            Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
            Using connection As New SqlConnection(conString)
    
                Dim TheSameLevelUnitsSet As SqlDataReader
    
                connection.Open()
    
                TDClass.PopulateTheSameLevelUnitsSet(UserName, Indx)
                queryString = "SELECT Indx FROM TheSameLevelUnitsSet WHERE LoadedByUserName=@UN"
                Dim GetTheSameLevelUnitsSet As New SqlCommand(queryString, connection)
                GetTheSameLevelUnitsSet.Parameters.Add("@UN", SqlDbType.NVarChar)
                GetTheSameLevelUnitsSet.Parameters("@UN").Value = UserName
                TheSameLevelUnitsSet = GetTheSameLevelUnitsSet.ExecuteReader()
    
                If TheSameLevelUnitsSet.HasRows Then
                    Do While TheSameLevelUnitsSet.Read()
                        If IsDBNull(TheSameLevelUnitsSet(0)) = False And TheSameLevelUnitsSet(0) <> Indx Then
                            AddNewToTarget(TheSameLevelUnitsSet(0), UserName)
                        End If
                    Loop
                End If
    
            End Using
        End Sub
    
        Public Shared Sub AddNewToTarget(ByVal Indx As Integer, ByVal UserName As String)
    
            Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
            Using connection As New SqlConnection(conString)
    
    
                connection.Open()
    
    
                Dim queryString As String = "INSERT INTO NewToTargets(Indx, LoadedByUserName) VALUES(@Ix,@UN)"
                Dim AddNewToTarget As New SqlCommand(queryString, connection)
                AddNewToTarget.Parameters.Add("@Ix", SqlDbType.Int)
                AddNewToTarget.Parameters("@Ix").Value = Indx
                AddNewToTarget.Parameters.Add("@UN", SqlDbType.NVarChar)
                AddNewToTarget.Parameters("@UN").Value = UserName
                AddNewToTarget.ExecuteNonQuery()
    
            End Using
    
        End Sub
    
        Public Shared Sub RemoveToTarget(ByVal Indx As Integer, ByVal UN As String)
            Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
            Using connection As New SqlConnection(conString)
    
                connection.Open()
    
                Dim queryString As String = "DELETE FROM NewToTargets WHERE (Indx = @IX) AND (LoadedByUserName = @UN)"
                Dim RemoveToTargetQuery As New SqlCommand(queryString, connection)
                RemoveToTargetQuery.Parameters.Add("@Ix", SqlDbType.Int)
                RemoveToTargetQuery.Parameters("@Ix").Value = Indx
                RemoveToTargetQuery.Parameters.Add("@UN", SqlDbType.NVarChar)
                RemoveToTargetQuery.Parameters("@UN").Value = UserName
                RemoveToTargetQuery.ExecuteNonQuery()
            End Using
        End Sub
    
        Public Shared Sub PushTheUnderlyingUnitsToTargets(ByVal UserName As String)
    
            Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
            Using connection As New SqlConnection(conString)
    
                connection.Open()
    
                Dim queryString As String = "INSERT INTO NewToTargets (Indx, LoadedByUserName) SELECT Indx, LoadedByUserName FROM UnderlyingUnits WHERE (LoadedByUserName = @UN)"
                Dim PushUnderlyingUnitsToTargetsQuery As New SqlCommand(queryString, connection)
                PushUnderlyingUnitsToTargetsQuery.Parameters.Add("@UN", SqlDbType.NVarChar)
                PushUnderlyingUnitsToTargetsQuery.Parameters("@UN").Value = UserName
                PushUnderlyingUnitsToTargetsQuery.ExecuteNonQuery()
            End Using
    
        End Sub
    
        Public Shared Sub PushTheExternalEntitiesToTargets(ByVal UserName As String)
    
            Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
            Using connection As New SqlConnection(conString)
    
                connection.Open()
    
                Dim queryString As String = "INSERT INTO NewToTargets (Indx,Name, LoadedByUserName) SELECT Indx,Name,@UN FROM ExternalEntities"
                Dim PushExternalEntitiesToTargetsQuery As New SqlCommand(queryString, connection)
                PushExternalEntitiesToTargetsQuery.Parameters.Add("@UN", SqlDbType.NVarChar)
                PushExternalEntitiesToTargetsQuery.Parameters("@UN").Value = UserName
                PushExternalEntitiesToTargetsQuery.ExecuteNonQuery()
            End Using
        End Sub
    
        Public Shared Sub PlugTheToTargetNames()
    
            Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
            Using connection As New SqlConnection(conString)
                Dim QueryString As String
    
                connection.Open()
    
                QueryString = "UPDATE NewToTargets SET Name = AdministrationUnits.Name FROM AdministrationUnits INNER JOIN NewToTargets ON AdministrationUnits.Indx = NewToTargets.Indx WHERE (LoadedByUserName=@UN)"
                Dim PlugAdminUnits As New SqlCommand(QueryString, connection)
                PlugAdminUnits.Parameters.Add("@UN", SqlDbType.NVarChar)
                PlugAdminUnits.Parameters("@UN").Value = UserName
                PlugAdminUnits.ExecuteNonQuery()
    
            End Using
    
        End Sub
    
        Public Shared Sub ClearToTargets(UserName As String)
    
            Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
            Using connection As New SqlConnection(conString)
    
    
                connection.Open()
    
    
                Dim queryString As String
                queryString = "DELETE FROM NewToTargets WHERE (LoadedByUserName=@UN)"
                Dim DelCommand As New SqlCommand(queryString, connection)
                DelCommand.Parameters.Add("@UN", SqlDbType.NVarChar)
                DelCommand.Parameters("@UN").Value = UserName
                DelCommand.ExecuteNonQuery()
    
            End Using
        End Sub
    
        Public Shared Sub ClearFromToTargets(UserName As String)
    
            Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
            Using connection As New SqlConnection(conString)
    
                connection.Open()
    
    
                Dim queryString As String
                queryString = "DELETE FROM NewFromTargets WHERE (LoadedByUserName=@UN)"
                Dim DelCommand As New SqlCommand(queryString, connection)
                DelCommand.Parameters.Add("@UN", SqlDbType.NVarChar)
                DelCommand.Parameters("@UN").Value = UserName
                DelCommand.ExecuteNonQuery()
    
    
            End Using
    
        End Sub
    
        Public Shared Sub AddNewFromTarget(ByVal Indx As Integer, ByVal UserName As String)
    
            Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
            Using connection As New SqlConnection(conString)
    
                connection.Open()
    
                Dim queryString As String = "INSERT INTO NewFromTargets(Indx, LoadedByUserName) VALUES(@Ix,@UN)"
                Dim AddNewFromTarget As New SqlCommand(queryString, connection)
                AddNewFromTarget.Parameters.Add("@Ix", SqlDbType.Int)
                AddNewFromTarget.Parameters("@Ix").Value = Indx
                AddNewFromTarget.Parameters.Add("@UN", SqlDbType.NVarChar)
                AddNewFromTarget.Parameters("@UN").Value = UserName
                AddNewFromTarget.ExecuteNonQuery()
            End Using
    
        End Sub
    
        Public Shared Sub PlugTheFromTargetNames()
    
            Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
            Using connection As New SqlConnection(conString)
                Dim QueryString As String
                connection.Open()
    
                QueryString = "UPDATE NewFromTargets SET Name = AdministrationUnits.Name FROM AdministrationUnits INNER JOIN NewFromTargets ON AdministrationUnits.Indx = NewFromTargets.Indx WHERE (LoadedByUserName=@UN)"
                Dim PlugAdminUnits As New SqlCommand(QueryString, connection)
                PlugAdminUnits.Parameters.Add("@UN", SqlDbType.NVarChar)
                PlugAdminUnits.Parameters("@UN").Value = UserName
                PlugAdminUnits.ExecuteNonQuery()
    
                QueryString = "DELETE FROM NewFromTargets WHERE (Name is Null)"
                Dim DeleteNullNewFromNames As New SqlCommand(QueryString, connection)
                DeleteNullNewFromNames.ExecuteNonQuery()
    
            End Using
    
        End Sub
    
        Public Shared Sub PushTheExternalEntitiesFromTargets(ByVal UserName As String)
    
            Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
            Using connection As New SqlConnection(conString)
                connection.Open()
                Dim queryString As String = "INSERT INTO NewFromTargets (Indx,Name, LoadedByUserName) SELECT Indx,Name,@UN FROM ExternalEntities"
                Dim PushExternalEntitiesFromTargetsQuery As New SqlCommand(queryString, connection)
                PushExternalEntitiesFromTargetsQuery.Parameters.Add("@UN", SqlDbType.NVarChar)
                PushExternalEntitiesFromTargetsQuery.Parameters("@UN").Value = UserName
                PushExternalEntitiesFromTargetsQuery.ExecuteNonQuery()
            End Using
        End Sub
    
        Public Shared Sub PushtheNewFromUnits(ByVal UserName As String)
    
            Dim queryString As String
            Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
            Using connection As New SqlConnection(conString)
    
                connection.Open()
    
    
    
                queryString = "SELECT Indx FROM Employees WHERE (UserName=@UN)"
                Dim LoginUserIndxSelectCommand As New SqlCommand(queryString, connection)
                LoginUserIndxSelectCommand.Parameters.Add("@UN", SqlDbType.NVarChar)
                LoginUserIndxSelectCommand.Parameters("@UN").Value = UserName
                Dim LoginUserIndx = LoginUserIndxSelectCommand.ExecuteScalar()
                UserIndx = LoginUserIndx
    
                'queryString = "INSERT INTO NewFromTargets(Indx,LoadedByUserName) SELECT UnitIndx,@UN FROM UnitsHeads WHERE (HeadIndx=@LoginUserIndx) AND (CAST (GETDATE() AS DateTime) BETWEEN Since AND Until)"
                queryString = "INSERT INTO NewFromTargets(Indx,LoadedByUserName) " &
                              "SELECT DISTINCT UnitsHeads.UnitIndx,@UN " &
                              "FROM AdministrationUnits INNER JOIN UnitsHeads ON AdministrationUnits.Indx = UnitsHeads.UnitIndx " &
                              "WHERE (HeadIndx=@LoginUserIndx) And (CAST(GETDATE() AS DateTime) BETWEEN UnitsHeads.Since And UnitsHeads.Until) And (CAST(GETDATE() AS DateTime) BETWEEN AdministrationUnits.FromDate And AdministrationUnits.ToDate)"
                Dim LoginUserUnitSelectCommand As New SqlCommand(queryString, connection)
                LoginUserUnitSelectCommand.Parameters.Add("@LoginUserIndx", SqlDbType.Int)
                LoginUserUnitSelectCommand.Parameters("@LoginUserIndx").Value = UserIndx
                LoginUserUnitSelectCommand.Parameters.Add("@UN", SqlDbType.NVarChar)
                LoginUserUnitSelectCommand.Parameters("@UN").Value = UserName
                LoginUserUnitSelectCommand.ExecuteNonQuery()
    
                '******************************************
                'turn it to comment
                'PushTheExternalEntitiesFromTargets(UserName)
                '******************************************
    
                queryString = "SELECT UnitIndx FROM UnitsHeads WHERE (HeadIndx=@LoginUserIndx) AND (CAST (GETDATE() AS DateTime) BETWEEN Since AND Until)"
                Dim GetUserUnit As New SqlCommand(queryString, connection)
                GetUserUnit.Parameters.Add("@LoginUserIndx", SqlDbType.Int)
                GetUserUnit.Parameters("@LoginUserIndx").Value = UserIndx
                GetUserUnit.Parameters.Add("@UN", SqlDbType.NVarChar)
                GetUserUnit.Parameters("@UN").Value = UserName
                Dim UserUnit As Integer = GetUserUnit.ExecuteScalar()
    
                queryString = "SELECT ReportingTo FROM AdministrationUnits WHERE (Indx=@Ix)"
                Dim GetUpLevelIndx As New SqlCommand(queryString, connection)
                GetUpLevelIndx.Parameters.Add("@Ix", SqlDbType.Int)
                GetUpLevelIndx.Parameters("@Ix").Value = UserUnit
                If IsDBNull(GetUpLevelIndx.ExecuteScalar()) Then
                    UpperLevelIndx = 0
                Else
                    UpperLevelIndx = GetUpLevelIndx.ExecuteScalar()
                End If
    
    
            End Using
    
        End Sub
    
        Protected Sub SourceName_TextChanged(sender As Object, e As System.EventArgs) Handles SourceName.TextChanged
    
            Dim TargetNameSelection As Integer
            TargetNameSelection = TargetName.SelectedValue
    
            'MakeTheExchange
            RemoveSourceNameSelectedIndxFromTargetName()
    
            Dim vListItem As ListItem = TargetName.Items.FindByValue(TargetNameSelection)
    
            If Not vListItem Is Nothing Then
                TargetName.SelectedValue = TargetNameSelection
            End If
    
            StorageUnit = SourceName.SelectedValue
            If CheckIfExternal(SourceName.SelectedValue) = 0 Then
                StorageUnit = SourceName.SelectedValue
                LetterIDPublic = TDClass.GenerateNewID(StorageUnit)
                LetterIDTxtBox.Text = LetterIDPublic
            Else
                AloneCB.Checked = True
                TargetName.Enabled = True
                MultiCB.Checked = False
                OpenMultiTargets.Enabled = False
                OpenMultiTargets.BackColor = Drawing.Color.Gray
                PickToExEntity.Enabled = True
                PickToExEntity.BackColor = EnabledColor
    
                If CheckIfExternal(TargetName.SelectedValue) = 0 Then
                    StorageUnit = TargetName.SelectedValue
                    LetterIDPublic = TDClass.GenerateNewID(StorageUnit)
                    LetterIDTxtBox.Text = LetterIDPublic
                End If
            End If
    
    
            If TDClass.CheckIfExternal(SourceName.SelectedValue) = 1 Then
    
                If TDClass.IsAdministrator(UserName) = 1 Then
                    TargetName.SelectedValue = 90001
                Else
                    TargetName.SelectedValue = LoginingIndx
                End If
    
                TargetName.SelectedValue = LoginingIndx
                StorageUnit = TargetName.SelectedValue
                LetterIDPublic = TDClass.GenerateNewID(StorageUnit)
                LetterIDTxtBox.Text = LetterIDPublic
                'TargetName.Enabled = False
                AloneCB.Checked = True
                AloneCB.Enabled = False
                MultiCB.Checked = False
                MultiCB.Enabled = False
                OpenMultiTargets.Enabled = False
                OpenMultiTargets.BackColor = DisabledColor
                PickToExEntity.Enabled = False
                PickToExEntity.BackColor = DisabledColor
            Else
                StorageUnit = SourceName.SelectedValue
                LetterIDPublic = TDClass.GenerateNewID(StorageUnit)
                LetterIDTxtBox.Text = LetterIDPublic
                TargetName.Enabled = True
                AloneCB.Checked = True
                AloneCB.Enabled = True
                MultiCB.Checked = False
                MultiCB.Enabled = True
                OpenMultiTargets.Enabled = False
                OpenMultiTargets.BackColor = DisabledColor
                PickToExEntity.Enabled = True
                PickToExEntity.BackColor = EnabledColor
            End If
    
    
    
    
    
        End Sub
    
        Public Sub SetSourceNameInitialValue()
    
    
    
            UnitIndx = TDClass.DetectUserMainUnit(UserName)
    
            If UnitIndx > 0 Then
                SourceName.SelectedValue = UnitIndx
                If LetterIDTxtBox.Text = "" Then
                    StorageUnit = UnitIndx
                    LetterIDPublic = TDClass.GenerateNewID(StorageUnit)
                    LetterIDTxtBox.Text = LetterIDPublic
                End If
            End If
    
            'End Using
        End Sub
    
        Public Sub SetTargetNameInitialValue(ByVal username As String)
    
            Dim queryString As String
            Dim TargetNameInitVal As Integer
            Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
            Using connection As New SqlConnection(conString)
    
                connection.Open()
    
                queryString = "SELECT Min(Indx) FROM NewToTargets WHERE (Indx <> @Ix) AND (LoadedByUserName=@UN)"
                Dim TargetNameInitValQuery As New SqlCommand(queryString, connection)
                TargetNameInitValQuery.Parameters.Add("@Ix", SqlDbType.Int)
                TargetNameInitValQuery.Parameters("@Ix").Value = SourceName.SelectedValue
                TargetNameInitValQuery.Parameters.Add("@UN", SqlDbType.NVarChar)
                TargetNameInitValQuery.Parameters("@UN").Value = username
                TargetNameInitVal = TargetNameInitValQuery.ExecuteScalar()
                TargetName.SelectedValue = TargetNameInitVal
    
            End Using
    
        End Sub
    
        Protected Sub TargetName_TextChanged(sender As Object, e As System.EventArgs) Handles TargetName.TextChanged
    
            StorageUnit = SourceName.SelectedValue
            If CheckIfExternal(SourceName.SelectedValue) = 0 Then
                StorageUnit = SourceName.SelectedValue
                LetterIDPublic = TDClass.GenerateNewID(StorageUnit)
                LetterIDTxtBox.Text = LetterIDPublic
            Else
                If CheckIfExternal(TargetName.SelectedValue) = 0 Then
                    StorageUnit = TargetName.SelectedValue
                    LetterIDPublic = TDClass.GenerateNewID(StorageUnit)
                    LetterIDTxtBox.Text = LetterIDPublic
                End If
            End If
    
            If CheckIfExternal(CInt(TargetName.SelectedValue)) = 1 Then
                SourceName.SelectedValue = LoginingIndx
            End If
    
        End Sub
    
        Protected Sub BothExternalValidator_ServerValidate(source As Object, args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles BothExternalValidator.ServerValidate
            If CheckIfExternal(SourceName.SelectedValue) = 1 And CheckIfExternal(TargetName.SelectedValue) = 1 Then
                args.IsValid = False
            End If
        End Sub
    
        Protected Sub NoneUserValidator_ServerValidate(source As Object, args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles NoneUserValidator.ServerValidate
    
            If TDClass.IsAuthorized(SourceName.SelectedValue, Session("UserName")) = False And TDClass.IsAuthorized(TargetName.SelectedValue, Session("UserName")) = False Then
                args.IsValid = False
            End If
    
    
        End Sub
    
        Protected Sub SenderNotUser_ServerValidate(source As Object, args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles SenderNotUser.ServerValidate
            If CheckIfExternal(SourceName.SelectedValue) = 0 And CheckIfExternal(TargetName.SelectedValue) = 0 And TDClass.IsAuthorized(SourceName.SelectedValue, Session("UserName")) = False Then
                args.IsValid = False
            End If
        End Sub
    
        Protected Sub PostTypeDDL_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles PostTypeDDL.SelectedIndexChanged
            If PostTypeDDL.Text = "للعلم" Then
                RAPTxtBox.Text = ""
                RAPTxtBox.Enabled = False
            ElseIf PostTypeDDL.Text = "طلب" Then
                RAPTxtBox.Enabled = True
                RAPTxtBox.Text = 7
            End If
        End Sub
    
        'Protected Sub RAPCustomeValidator_ServerValidate(source As Object, args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles RAPCustomeValidator.ServerValidate
        '    If PostTypeDDL.Text = "طلب" Then
        '        If RAPTxtBox.Text = "" Then
        '            RAPCustomeValidator.ErrorMessage = "لم تقم بإدخال مهلة الرد"
        '            args.IsValid = False
        '        ElseIf IsNumeric(RAPTxtBox.Text) = False Then
        '            RAPCustomeValidator.ErrorMessage = "مهلة الرد الذي تم إدخالها غير صحيحة"
        '            args.IsValid = False
        '        End If
        '    End If
        'End Sub
    
        Public Shared Sub ClearCCToTargets(UserName As String)
    
            Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
            Using connection As New SqlConnection(conString)
                connection.Open()
    
                Dim queryString As String
                queryString = "DELETE FROM CCTargetUnits WHERE (LoadedByUserName=@UN)"
                Dim DelCommand As New SqlCommand(queryString, connection)
                DelCommand.Parameters.Add("@UN", SqlDbType.NVarChar)
                DelCommand.Parameters("@UN").Value = UserName
                DelCommand.ExecuteNonQuery()
    
                queryString = "DELETE FROM CCFromUnits WHERE (LoadedByUserName=@UN)"
                Dim DelCommand1 As New SqlCommand(queryString, connection)
                DelCommand1.Parameters.Add("@UN", SqlDbType.NVarChar)
                DelCommand1.Parameters("@UN").Value = UserName
                DelCommand1.ExecuteNonQuery()
    
    
                queryString = "INSERT INTO CCFromUnits(Indx,Name,LoadedByUserName) " & _
                              "SELECT DISTINCT Indx,Name,@UN " & _
                              "FROM AdministrationUnits "
                Dim LoadCCFromUnitsInitial As New SqlCommand(queryString, connection)
                LoadCCFromUnitsInitial.Parameters.Add("@UN", SqlDbType.NVarChar)
                LoadCCFromUnitsInitial.Parameters("@UN").Value = UserName
                LoadCCFromUnitsInitial.ExecuteNonQuery()
    
            End Using
    
        End Sub
    
        Public Shared Sub PrepareTags(UserName As String)
    
            Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
            Using connection As New SqlConnection(conString)
                connection.Open()
    
                Dim queryString As String
                queryString = "DELETE FROM SelectedTags WHERE (LoadedByUserName=@UN)"
                Dim DelCommand As New SqlCommand(queryString, connection)
                DelCommand.Parameters.Add("@UN", SqlDbType.NVarChar)
                DelCommand.Parameters("@UN").Value = UserName
                DelCommand.ExecuteNonQuery()
    
                queryString = "DELETE FROM UnSelectedTags WHERE (LoadedByUserName=@UN)"
                Dim DelCommand1 As New SqlCommand(queryString, connection)
                DelCommand1.Parameters.Add("@UN", SqlDbType.NVarChar)
                DelCommand1.Parameters("@UN").Value = UserName
                DelCommand1.ExecuteNonQuery()
    
    
                queryString = "INSERT INTO UnSelectedTags(KeyTag,LoadedByUserName) " & _
                              "SELECT DISTINCT AllTags.KeyTag,@UN " & _
                              "FROM AllTags WHERE ((AdminUnit=0) OR (AdminUnit is Null))"
                Dim LoadInitialKeyTags1 As New SqlCommand(queryString, connection)
                LoadInitialKeyTags1.Parameters.Add("@UN", SqlDbType.NVarChar)
                LoadInitialKeyTags1.Parameters("@UN").Value = UserName
                LoadInitialKeyTags1.ExecuteNonQuery()
    
                queryString = "INSERT INTO UnSelectedTags(KeyTag,LoadedByUserName) " & _
                              "SELECT DISTINCT AllTags.KeyTag,@UN " & _
                              "FROM AllTags WHERE (AdminUnit=@AU) AND (AddRemove=@AR)"
                Dim LoadInitialKeyTags2 As New SqlCommand(queryString, connection)
                LoadInitialKeyTags2.Parameters.Add("@UN", SqlDbType.NVarChar)
                LoadInitialKeyTags2.Parameters("@UN").Value = UserName
                LoadInitialKeyTags2.Parameters.Add("@AU", SqlDbType.Int)
                LoadInitialKeyTags2.Parameters("@AU").Value = StorageUnit
                LoadInitialKeyTags2.Parameters.Add("@AR", SqlDbType.NVarChar)
                LoadInitialKeyTags2.Parameters("@AR").Value = "add"
                LoadInitialKeyTags2.ExecuteNonQuery()
    
                queryString = "DELETE FROM UnSelectedTags " & _
                              "FROM AllTags INNER JOIN UnSelectedTags ON AllTags.KeyTag = UnSelectedTags.KeyTag " & _
                              "WHERE  (UnSelectedTags.LoadedByUserName = @UN) AND (AllTags.AdminUnit = @AU) AND (AllTags.AddRemove = @AR)"
                Dim LoadInitialKeyTags3 As New SqlCommand(queryString, connection)
                LoadInitialKeyTags3.Parameters.Add("@UN", SqlDbType.NVarChar)
                LoadInitialKeyTags3.Parameters("@UN").Value = UserName
                LoadInitialKeyTags3.Parameters.Add("@AU", SqlDbType.Int)
                LoadInitialKeyTags3.Parameters("@AU").Value = StorageUnit
                LoadInitialKeyTags3.Parameters.Add("@AR", SqlDbType.NVarChar)
                LoadInitialKeyTags3.Parameters("@AR").Value = "remove"
                LoadInitialKeyTags3.ExecuteNonQuery()
    
    
                queryString = "DELETE FROM AllTagsTemp WHERE (LoadedByUserName=@UN)"
                Dim ClearAllTagsTemp As New SqlCommand(queryString, connection)
                ClearAllTagsTemp.Parameters.Add("@UN", SqlDbType.NVarChar)
                ClearAllTagsTemp.Parameters("@UN").Value = UserName
                ClearAllTagsTemp.ExecuteNonQuery()
    
    
            End Using
    
        End Sub
    
        Public Sub ComposeNewMessageCopies()
    
            Dim UserName As String = Session("username")
            'Dim Source As Integer = UnitIndx
            Dim Source As Integer
            Dim RefNo As String = LetterIDTxtBox.Text
            Dim PostType As String = "نسخة"
            Dim Subject As String = SubjectTxtBox.Text
            Dim Comments As String = CommentsTxtBox.Text
            Dim AAL As String = LetterIDTxtBox.Text
            Dim CCList As SqlDataReader
            Dim Importance As String
            Dim PostTime As DateTime
    
            If OtherDate.Checked = True Then
                PostTime = PostDate
            Else
                PostTime = Now()
            End If
    
            Importance = ImportanceDD.SelectedValue
            Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
            Using connection As New SqlConnection(conString)
                connection.Open()
    
                Dim queryString As String = "SELECT DISTINCT Indx FROM CCTargetUnits WHERE (LoadedByUserName=@UN)"
                Dim BuildCCList As New SqlCommand(queryString, connection)
                BuildCCList.Parameters.Add("@UN", SqlDbType.NVarChar)
                BuildCCList.Parameters("@UN").Value = UserName
                CCList = BuildCCList.ExecuteReader()
    
                If CCList.HasRows Then
                    Do While CCList.Read()
                        If IsDBNull(CCList(0)) = False Then
                            Dim Target As Integer = CCList(0)
    
                            Dim LetterID As String = TDClass.GenerateNewSubID(UnitIndx, RefNo)
    
                            If CheckIfExternal(SourceName.SelectedValue) = 0 Then
                                CopyLettersIntoServer(LetterID, SourceName.SelectedValue)
                            Else
                                CopyLettersIntoServer(LetterID, CCList(0))
                            End If
    
    
                            Source = SourceName.SelectedValue
                            PushIntoPostings(UserName, RefNo, LetterID, Source, Target, Subject, Comments, "نسخة", Importance, AAL, 1, PostTime)
                            If IsTopSecret.Checked = True Then
                                AddPrivatePostingsRecords(LetterID)
                            End If
                        End If
                    Loop
                    CCList.Close()
                End If
    
            End Using
        End Sub
    
        Protected Sub OpenCCWindow_Click(sender As Object, e As EventArgs) Handles OpenCCWindow.Click
            Response.Write("<script>")
            Response.Write("window.open('CCPosting.aspx','_blank')")
            Response.Write("</script>")
        End Sub
    
        Protected Sub AloneCB_CheckedChanged(sender As Object, e As EventArgs) Handles AloneCB.CheckedChanged
            If AloneCB.Checked = False Then
                TargetName.Enabled = False
                MultiCB.Checked = True
                OpenMultiTargets.Enabled = True
                OpenMultiTargets.BackColor = EnabledColor
                PickToExEntity.Enabled = False
                PickToExEntity.BackColor = DisabledColor
    
                TargetName.Enabled = False
                TargetName.BackColor = Drawing.Color.WhiteSmoke
            Else
                TargetName.Enabled = True
                MultiCB.Checked = False
                OpenMultiTargets.Enabled = False
                OpenMultiTargets.BackColor = DisabledColor
                PickToExEntity.Enabled = True
                PickToExEntity.BackColor = EnabledColor
    
                TargetName.Enabled = True
                TargetName.BackColor = Drawing.Color.White
            End If
        End Sub
        Protected Sub MultiCB_CheckedChanged(sender As Object, e As EventArgs) Handles MultiCB.CheckedChanged
            If MultiCBUncheckable = 0 Then
                If MultiCB.Checked = False Then
                    TargetName.Enabled = True
                    AloneCB.Checked = True
                    OpenMultiTargets.Enabled = False
                    OpenMultiTargets.BackColor = DisabledColor
                    PickToExEntity.Enabled = True
                    PickToExEntity.BackColor = EnabledColor
                    '-----------------
                    TargetName.BackColor = Drawing.Color.White
                    '-----------------
                Else
                    If CheckIfExternal(SourceName.SelectedValue) = 1 Then
                        AloneCB.Checked = True
                        MultiCB.Checked = False
                    Else
                        TargetName.Enabled = False
                        AloneCB.Checked = False
                        OpenMultiTargets.Enabled = True
                        OpenMultiTargets.BackColor = EnabledColor
                        PickToExEntity.Enabled = False
                        PickToExEntity.BackColor = DisabledColor
    
                        TargetName.Enabled = False
                        TargetName.BackColor = Drawing.Color.WhiteSmoke
    
                    End If
                End If
            Else
                MultiCB.Checked = True
            End If
        End Sub
    
        Public Sub PushIntoPostings(ByVal UserName As String, ByVal RefNo As String, ByVal LetterID As String, ByVal Source As Integer, ByVal Target As Integer, ByVal Subject As String, ByVal Comments As String, ByVal PostType As String, ByVal Importance As String, ByVal AAL As String, ByVal LatePostingTime As Integer, ByVal PostTime As DateTime)
    
            Dim queryString As String
            Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
            Using connection As New SqlConnection(conString)
                connection.Open()
    
                queryString = "INSERT INTO Postings (LetterID, Source, Target, PostTime, PostType, Importance, RequiredAnsPeriod, Subject, Comments,  LoggingUserName,LoggingTime) VALUES (@LID,@SRC,@TGT,@PTime,@PType,@Imp,@RAP,@Subj,@Cmts,@UN,@LogTime)"
                Dim InsertNewPost As New SqlCommand(queryString, connection)
                InsertNewPost.Parameters.Add("@LID", SqlDbType.NVarChar)
                InsertNewPost.Parameters("@LID").Value = LetterID
                InsertNewPost.Parameters.Add("@SRC", SqlDbType.Int)
                InsertNewPost.Parameters("@SRC").Value = Source
                InsertNewPost.Parameters.Add("@TGT", SqlDbType.Int)
                InsertNewPost.Parameters("@TGT").Value = Target
                InsertNewPost.Parameters.Add("@PTime", SqlDbType.DateTime)
                If LatePostingTime = 1 Then
                    InfoCopyPostConsecutive = InfoCopyPostConsecutive + 1
                    InsertNewPost.Parameters("@PTime").Value = DateAdd(DateInterval.Second, 10 * InfoCopyPostConsecutive, PostTime)
                Else
                    InsertNewPost.Parameters("@PTime").Value = PostTime
                End If
                InsertNewPost.Parameters.Add("@PType", SqlDbType.NVarChar)
                InsertNewPost.Parameters("@PType").Value = PostType
                InsertNewPost.Parameters.Add("@Imp", SqlDbType.NVarChar)
                InsertNewPost.Parameters("@Imp").Value = Importance
                InsertNewPost.Parameters.Add("@RAP", SqlDbType.Int)
                InsertNewPost.Parameters("@RAP").Value = 0
                InsertNewPost.Parameters.Add("@Subj", SqlDbType.NVarChar)
                InsertNewPost.Parameters("@Subj").Value = Subject
                InsertNewPost.Parameters.Add("@Cmts", SqlDbType.NVarChar)
                InsertNewPost.Parameters("@Cmts").Value = Comments
                InsertNewPost.Parameters.Add("@UN", SqlDbType.NVarChar)
                InsertNewPost.Parameters("@UN").Value = UserName
                InsertNewPost.Parameters.Add("@LogTime", SqlDbType.DateTime)
                InsertNewPost.Parameters("@LogTime").Value = Now()
                'InsertNewPost.Parameters.Add("@AAL", SqlDbType.NVarChar)
                'InsertNewPost.Parameters("@AAL").Value = AAL
                InsertNewPost.ExecuteNonQuery()
    
                If RefNo <> "" Then
                    queryString = "UPDATE Postings SET RefNo=@RNO WHERE (LetterID=@LID)"
                    Dim SetRefNo As New SqlCommand(queryString, connection)
                    SetRefNo.Parameters.Add("@RNO", SqlDbType.NVarChar)
                    SetRefNo.Parameters("@RNO").Value = RefNo
                    SetRefNo.Parameters.Add("@LID", SqlDbType.NVarChar)
                    SetRefNo.Parameters("@LID").Value = LetterID
                    SetRefNo.ExecuteNonQuery()
                End If
    
                If AAL <> "" Then
                    queryString = "UPDATE Postings SET ActionAgainstLetter=@AAL WHERE (LetterID=@LID)"
                    Dim SetAAL As New SqlCommand(queryString, connection)
                    SetAAL.Parameters.Add("@AAL", SqlDbType.NVarChar)
                    SetAAL.Parameters("@AAL").Value = AAL
                    SetAAL.Parameters.Add("@LID", SqlDbType.NVarChar)
                    SetAAL.Parameters("@LID").Value = LetterID
                    SetAAL.ExecuteNonQuery()
                End If
    
                If TDClass.CheckIfExternal(SourceName.SelectedValue) = 1 Then
                    queryString = "SELECT COUNT(*) FROM IncomingLetterInfo WHERE (LoadedByUserIndx=@Ix)"
                    Dim CountIncomingLetterInfoRows As New SqlCommand(queryString, connection)
                    CountIncomingLetterInfoRows.Parameters.Add("@Ix", SqlDbType.Int)
                    CountIncomingLetterInfoRows.Parameters("@Ix").Value = TDClass.GetLoggingUserIndxValue(UserName)
                    Dim IncomingLetterInfoRows As Integer = CountIncomingLetterInfoRows.ExecuteScalar()
    
                    If IncomingLetterInfoRows > 0 Then
                        If InRefNo <> "" Then
                            queryString = "UPDATE Postings SET IncomeRefNo=@InRNo WHERE (LetterID=@LID)"
                            Dim PlugIncomingLetterInfo As New SqlCommand(queryString, connection)
                            PlugIncomingLetterInfo.Parameters.Add("@InRNo", SqlDbType.NVarChar)
                            PlugIncomingLetterInfo.Parameters.Add("@LID", SqlDbType.NVarChar)
                            PlugIncomingLetterInfo.Parameters("@InRNo").Value = InRefNo
                            PlugIncomingLetterInfo.Parameters("@LID").Value = LetterID
                            PlugIncomingLetterInfo.ExecuteNonQuery()
                        End If
    
                        If DateDiff(DateInterval.Day, InPostDate, Date.Parse("01-01-1900")) <> 0 Then
                            queryString = "UPDATE Postings SET IncomePostDate=@InPD WHERE (LetterID=@LID)"
                            Dim PlugIncomingLetterInfo As New SqlCommand(queryString, connection)
                            PlugIncomingLetterInfo.Parameters.Add("@InPD", SqlDbType.Date)
                            PlugIncomingLetterInfo.Parameters.Add("@LID", SqlDbType.NVarChar)
                            PlugIncomingLetterInfo.Parameters("@InPD").Value = InPostDate
                            PlugIncomingLetterInfo.Parameters("@LID").Value = LetterID
                            PlugIncomingLetterInfo.ExecuteNonQuery()
                        End If
                    End If
                End If
    
            End Using
    
        End Sub
    
        Public Sub CopyLettersIntoServer(ByVal LetterID As String, ByVal ThisStorageUnit As Integer)
    
            Dim TheSelectedFileSourcePath As String
    
    
            TheSelectedFileSourcePath = AttachmentsSelecter.FileName
            Dim DotPos As Integer = InStr(TheSelectedFileSourcePath, ".")
            Dim FileExtension As String = TheSelectedFileSourcePath.Substring(DotPos, Len(TheSelectedFileSourcePath) - DotPos)
            Dim LocalPath As String
    
            LocalPath = "~\PdfDirectory\"
            Dim FileToDelete As String = LocalPath & LetterID & ".doc"
            If System.IO.File.Exists(FileToDelete) = True Then
                System.IO.File.Delete(FileToDelete)
            End If
    
            FileToDelete = LocalPath & LetterID & ".docx"
            If System.IO.File.Exists(FileToDelete) = True Then
                System.IO.File.Delete(FileToDelete)
            End If
    
            FileToDelete = LocalPath & LetterID & ".pdf"
            If System.IO.File.Exists(FileToDelete) = True Then
                System.IO.File.Delete(FileToDelete)
            End If
    
            FileToDelete = LocalPath & LetterID & ".jpg"
            If System.IO.File.Exists(FileToDelete) = True Then
                System.IO.File.Delete(FileToDelete)
            End If
    
            FileToDelete = LocalPath & LetterID & ".TIF"
            If System.IO.File.Exists(FileToDelete) = True Then
                System.IO.File.Delete(FileToDelete)
            End If
    
            'Dim ServerPath As String = TDClass.GetTheServerStoragePath(ThisStorageUnit)
            'TheAttachedFileServerPath = ServerPath & LetterID & "." & FileExtension
            'AttachmentsSelecter.SaveAs(TheAttachedFileServerPath)
            If AttachmentsSelecter.FileName <> "" Then
                UploadCopyAttachments(ThisStorageUnit, LetterID)
            End If
    
        End Sub
    
        Public Shared Sub ClearNewPostFromTargetUnits(UserName As String)
    
            Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
            Using connection As New SqlConnection(conString)
                connection.Open()
    
                Dim queryString As String
                queryString = "DELETE FROM NewPostTargetUnits WHERE (LoadedByUserName=@UN)"
                Dim DelCommand As New SqlCommand(queryString, connection)
                DelCommand.Parameters.Add("@UN", SqlDbType.NVarChar)
                DelCommand.Parameters("@UN").Value = UserName
                DelCommand.ExecuteNonQuery()
    
                queryString = "DELETE FROM NewPostFromUnits WHERE (LoadedByUserName=@UN)"
                Dim DelCommand1 As New SqlCommand(queryString, connection)
                DelCommand1.Parameters.Add("@UN", SqlDbType.NVarChar)
                DelCommand1.Parameters("@UN").Value = UserName
                DelCommand1.ExecuteNonQuery()
    
    
                queryString = "INSERT INTO NewPostFromUnits(Indx,Name,LoadedByUserName) " & _
                              "SELECT DISTINCT Indx,Name,@UN " & _
                              "FROM AdministrationUnits "
                Dim LoadCCFromUnitsInitial As New SqlCommand(queryString, connection)
                LoadCCFromUnitsInitial.Parameters.Add("@UN", SqlDbType.NVarChar)
                LoadCCFromUnitsInitial.Parameters("@UN").Value = UserName
                LoadCCFromUnitsInitial.ExecuteNonQuery()
    
            End Using
    
        End Sub
    
        Protected Sub OpenMultiTargets_Click(sender As Object, e As EventArgs) Handles OpenMultiTargets.Click
            Response.Write("<script>")
            Response.Write("window.open('NewPostTargets.aspx','_blank')")
            Response.Write("</script>")
        End Sub
    
    
        Protected Sub NoRequestMultiTargets_ServerValidate(source As Object, args As ServerValidateEventArgs) Handles NoRequestMultiTargets.ServerValidate
            If PostTypeDDL.Text = "طلب" And MultiCB.Checked = True Then
                args.IsValid = False
            End If
        End Sub
    
        Protected Sub NoMultiTargetsSelected_ServerValidate(source As Object, args As ServerValidateEventArgs) Handles NoMultiTargetsSelected.ServerValidate
    
            Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
            Using connection As New SqlConnection(conString)
    
                connection.Open()
    
                Dim queryString As String = "SELECT Indx FROM NewPostTargetUnits WHERE (LoadedByUserName=@UN)"
                Dim GetTargetUnits As New SqlCommand(queryString, connection)
                GetTargetUnits.Parameters.Add("@UN", SqlDbType.NVarChar)
                GetTargetUnits.Parameters("@UN").Value = Session("username")
                Dim NewTargetUnits As SqlDataReader = GetTargetUnits.ExecuteReader()
    
                If NewTargetUnits.HasRows = False And MultiCB.Checked = True Then
                    args.IsValid = False
                End If
            End Using
        End Sub
    
        Public Sub SendLettertoMultiTargets()
    
            Dim UserName As String = Session("username")
            'Dim Source As Integer = UnitIndx
            Dim Source As Integer
            Dim RefNo As String = LetterIDTxtBox.Text
            Dim PostType As String = "للعلم"
            Dim Subject As String = SubjectTxtBox.Text
            Dim Comments As String = CommentsTxtBox.Text
            Dim AAL As String = LetterIDTxtBox.Text
            Dim TargetsList As SqlDataReader
            Dim IndxCounter As Integer = 0
            Dim Importance As String
            Dim PostTime As DateTime
    
            Importance = ImportanceDD.SelectedValue
            If OtherDate.Checked = True Then
                PostTime = PostDate
            Else
                PostTime = Now()
            End If
    
            Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
            Using connection As New SqlConnection(conString)
                connection.Open()
    
                Dim queryString As String = "SELECT DISTINCT Indx FROM NewPostTargetUnits WHERE (LoadedByUserName=@UN)"
                Dim BuildTargetsList As New SqlCommand(queryString, connection)
                BuildTargetsList.Parameters.Add("@UN", SqlDbType.NVarChar)
                BuildTargetsList.Parameters("@UN").Value = Session("username")
                TargetsList = BuildTargetsList.ExecuteReader()
    
                If TargetsList.HasRows Then
                    Do While TargetsList.Read()
                        If IsDBNull(TargetsList(0)) = False Then
                            Dim Target As Integer = TargetsList(0)
                            Dim LetterID As String = ""
    
                            '---------------------------------------------------------------------
                            If IndxCounter = 0 Then
                                LetterID = Trim(LetterIDTxtBox.Text)
                                RefNo = ""
                                If CheckIfExternal(SourceName.SelectedValue) = 0 Then
                                    CopyLettersIntoServer(LetterID, SourceName.SelectedValue)
                                Else
                                    CopyLettersIntoServer(LetterID, TargetsList(0))
                                End If
                            Else
                                RefNo = Trim(LetterIDTxtBox.Text)
                                LetterID = TDClass.GenerateNewSubID(UnitIndx, RefNo)
                                '************************************************
                                If CheckIfExternal(SourceName.SelectedValue) = 0 Then
                                    CopyLettersIntoServer(LetterID, SourceName.SelectedValue)
                                Else
                                    CopyLettersIntoServer(LetterID, TargetsList(0))
                                End If
                                '************************************************
                                'CopyLettersIntoServer(LetterID)
                            End If
                            IndxCounter = IndxCounter + 1
                            Source = SourceName.SelectedValue
                            '---------------------------------------------------------------------
                            PushIntoPostings(UserName, RefNo, LetterID, Source, Target, Subject, Comments, "للعلم", Importance, "", 0, PostTime)
                            If IsTopSecret.Checked = True Then
                                AddPrivatePostingsRecords(LetterID)
                            End If
                        End If
                    Loop
                    TargetsList.Close()
                End If
            End Using
    
        End Sub
    
        Protected Sub PickFromExEntity_Click(sender As Object, e As EventArgs) Handles PickFromExEntity.Click
            Session("NewPostTrigger") = "source"
            StoreFormValuesIntoSession()
            Response.Redirect("~\NewPosting\ExternalEntityPickingForm.aspx")
        End Sub
    
        Public Sub BuildTheNewToTargets(ByVal UserName As String)
    
            Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
            Using connection As New SqlConnection(conString)
                connection.Open()
    
                Dim queryString As String = "DELETE FROM NewToTargets WHERE (LoadedByUserName=@UN)"
                Dim DelCommand1 As New SqlCommand(queryString, connection)
                DelCommand1.Parameters.Add("@UN", SqlDbType.NVarChar)
                DelCommand1.Parameters("@UN").Value = Session("username")
                DelCommand1.ExecuteNonQuery()
    
                queryString = "INSERT INTO NewToTargets (Indx,Name, LoadedByUserName) " &
                               "SELECT Indx,Name,@UN FROM AdministrationUnits " &
                               "WHERE (CAST (GETDATE() AS DateTime) BETWEEN FromDate And ToDate)"
                Dim PushAllAdminUnitsintoNewToTargets As New SqlCommand(queryString, connection)
                PushAllAdminUnitsintoNewToTargets.Parameters.Add("@UN", SqlDbType.NVarChar)
                PushAllAdminUnitsintoNewToTargets.Parameters("@UN").Value = UserName
                PushAllAdminUnitsintoNewToTargets.ExecuteNonQuery()
    
                queryString = "DELETE FROM NewToTargetsA WHERE (LoadedByUserName=@UN)"
                Dim DelCommandA As New SqlCommand(queryString, connection)
                DelCommandA.Parameters.Add("@UN", SqlDbType.NVarChar)
                DelCommandA.Parameters("@UN").Value = Session("username")
                DelCommandA.ExecuteNonQuery()
    
                queryString = "INSERT INTO NewToTargetsA (Indx, LoadedByUserName) SELECT UnitIndx,@UN FROM UnitsHeads WHERE (HeadIndx=@LoginUserIndx) And (CAST (GETDATE() AS DateTime) BETWEEN Since And Until)"
                Dim BuildNewToTargetsA As New SqlCommand(queryString, connection)
                BuildNewToTargetsA.Parameters.Add("@UN", SqlDbType.NVarChar)
                BuildNewToTargetsA.Parameters("@UN").Value = UserName
                BuildNewToTargetsA.Parameters.Add("@LoginUserIndx", SqlDbType.Int)
                BuildNewToTargetsA.Parameters("@LoginUserIndx").Value = UserIndx
                BuildNewToTargetsA.ExecuteNonQuery()
    
                queryString = "UPDATE NewToTargetsA SET Name = AdministrationUnits.Name FROM AdministrationUnits INNER JOIN NewToTargetsA ON AdministrationUnits.Indx = NewToTargetsA.Indx WHERE (LoadedByUserName=@UN)"
                Dim PlugAdminUnits As New SqlCommand(queryString, connection)
                PlugAdminUnits.Parameters.Add("@UN", SqlDbType.NVarChar)
                PlugAdminUnits.Parameters("@UN").Value = UserName
                PlugAdminUnits.ExecuteNonQuery()
    
    
            End Using
        End Sub
        Protected Sub PickToExEntity_Click(sender As Object, e As EventArgs) Handles PickToExEntity.Click
            Session("NewPostTrigger") = "target"
            StoreFormValuesIntoSession()
            Response.Redirect("~\NewPosting\ExternalEntityPickingForm.aspx")
        End Sub
    
        Public Sub StoreFormValuesIntoSession()
    
    
            Session("NewPostSourceValue") = SourceName.SelectedValue
            Session("NewPostTargetValue") = TargetName.SelectedValue
    
            Session("OldPostSourceValue") = SourceName.SelectedValue
    
            Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
            Using connection As New SqlConnection(conString)
                connection.Open()
    
                Dim queryString As String
                If CheckIfExternal(CInt(SourceName.SelectedValue)) = 0 Then
                    queryString = "SELECT Name FROM AdministrationUnits WHERE (Indx=@Ix)"
                    Dim GetSourceName As New SqlCommand(queryString, connection)
                    GetSourceName.Parameters.Add("@Ix", SqlDbType.Int)
                    GetSourceName.Parameters("@Ix").Value = CInt(SourceName.SelectedValue)
                    If IsDBNull(GetSourceName.ExecuteScalar()) = False Then
                        Session("NewPostSourceName") = GetSourceName.ExecuteScalar()
                    End If
                Else
                    queryString = "SELECT Name FROM ExternalEntities WHERE (Indx=@Ix)"
                    Dim GetSourceName As New SqlCommand(queryString, connection)
                    GetSourceName.Parameters.Add("@Ix", SqlDbType.Int)
                    GetSourceName.Parameters("@Ix").Value = CInt(SourceName.SelectedValue)
                    If IsDBNull(GetSourceName.ExecuteScalar()) = False Then
                        Session("NewPostSourceName") = GetSourceName.ExecuteScalar()
                    End If
                End If
    
    
                If CheckIfExternal(CInt(TargetName.SelectedValue)) = 0 Then
                    queryString = "SELECT Name FROM AdministrationUnits WHERE (Indx=@Ix)"
                    Dim GetTargetName As New SqlCommand(queryString, connection)
                    GetTargetName.Parameters.Add("@Ix", SqlDbType.Int)
                    GetTargetName.Parameters("@Ix").Value = CInt(TargetName.SelectedValue)
                    If IsDBNull(GetTargetName.ExecuteScalar()) = False Then
                        Session("NewPostTargetName") = GetTargetName.ExecuteScalar()
                    End If
                Else
                    queryString = "SELECT Name FROM ExternalEntities WHERE (Indx=@Ix)"
                    Dim GetTargetName As New SqlCommand(queryString, connection)
                    GetTargetName.Parameters.Add("@Ix", SqlDbType.Int)
                    GetTargetName.Parameters("@Ix").Value = CInt(TargetName.SelectedValue)
                    If IsDBNull(GetTargetName.ExecuteScalar()) = False Then
                        Session("NewPostTargetName") = GetTargetName.ExecuteScalar()
                    End If
                End If
    
            End Using
    
            If AloneCB.Checked = True Then
                Session("NewPostAloneCB") = "true"
            ElseIf AloneCB.Checked = False Then
                Session("NewPostAloneCB") = "false"
            End If
    
            If MultiCB.Checked = True Then
                Session("NewPostMultiCB") = "true"
            ElseIf MultiCB.Checked = False Then
                Session("NewPostMultiCB") = "false"
            End If
    
            If NowDate.Checked = True Then
                Session("PostDateNowDate") = "true"
            Else
                Session("PostDateNowDate") = "false"
            End If
    
            If IsTopSecret.Checked = True Then
                Session("NewPostIsTopSecret") = "true"
            Else
                Session("NewPostIsTopSecret") = "false"
            End If
    
            Session("NewPostDateVal") = PostDateTxtBox.Text
    
            Session("NewPostLetterIDPublic") = LetterIDTxtBox.Text
            Session("NewPostFollowUpID") = FollowUpID.Text
            Session("NewPostSubject") = SubjectTxtBox.Text
            Session("NewPostComments") = CommentsTxtBox.Text
            Session("NewPostTypeDDLValue") = PostTypeDDL.SelectedValue
            Session("NewPostRAPTxtBox") = RAPTxtBox.Text
            Session("NewPostImportanceValue") = ImportanceDD.SelectedValue
            '*****************************************************************
            Session("NewPostExEntityBack") = 1
        End Sub
    
        Public Sub StorePostingTags()
    
            Dim UserName As String = Session("username")
            Dim RefNo As String = Trim(LetterIDTxtBox.Text)
    
            Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
            Using connection As New SqlConnection(conString)
    
                connection.Open()
    
                Dim queryString As String = "INSERT INTO PostingsTags(KeyTag) SELECT DISTINCT(KeyTag) FROM SelectedTags WHERE (LoadedByUserName=@UN)"
                Dim InsertPostingTags As New SqlCommand(queryString, connection)
                InsertPostingTags.Parameters.Add("@UN", SqlDbType.NVarChar)
                InsertPostingTags.Parameters("@UN").Value = UserName
                InsertPostingTags.ExecuteNonQuery()
    
                queryString = "UPDATE PostingsTags SET RefNo=@RNo WHERE (RefNo Is Null)"
                Dim PlugRefNo As New SqlCommand(queryString, connection)
                PlugRefNo.Parameters.Add("@RNO", SqlDbType.NVarChar)
                PlugRefNo.Parameters("@RNO").Value = RefNo
                PlugRefNo.ExecuteNonQuery()
    
    
            End Using
        End Sub
    
        Protected Sub OpenTagsWindow_Click(sender As Object, e As EventArgs) Handles OpenTagsWindow.Click
            Response.Write("<script>")
            Response.Write("window.open('TagsWindow.aspx','_blank')")
            Response.Write("</script>")
        End Sub
    
    
        Protected Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowDataBound
    
            Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
            Using connection As New SqlConnection(conString)
                Dim queryString As String
                connection.Open()
    
                If e.Row.RowType = DataControlRowType.DataRow Then
                    Dim MyRowView As DataRowView = CType(e.Row.DataItem, DataRowView)
    
                    If MyRowView("LoadedByUserName") = Session("username") Then
    
                        If MyRowView("AddRemove") = "Add" Then
    
    
                            If MyRowView("AdditionStatus") = "AllUnits" Then
    
                                queryString = "DELETE FROM AllTags WHERE (KeyTag=@Tag) AND ((AdminUnit=0) or (AdminUnit is Null)) AND (AddRemove is Null)"
                                Dim ClearPreviousRecords As New SqlCommand(queryString, connection)
                                ClearPreviousRecords.Parameters.Add("@Tag", SqlDbType.NVarChar)
                                ClearPreviousRecords.Parameters("@Tag").Value = MyRowView("keytag")
                                ClearPreviousRecords.ExecuteNonQuery()
    
                                queryString = "INSERT INTO AllTags(KeyTag) " & _
                                              "VALUES(@Tag)"
                                Dim StoreNewTag As New SqlCommand(queryString, connection)
                                StoreNewTag.Parameters.Add("@Tag", SqlDbType.NVarChar)
                                StoreNewTag.Parameters("@Tag").Value = MyRowView("keytag")
                                StoreNewTag.ExecuteNonQuery()
    
                            ElseIf MyRowView("AdditionStatus") = "ThisUnit" Then
    
                                queryString = "DELETE FROM AllTags WHERE (KeyTag=@Tag) AND (AdminUnit=@AU) AND (AddRemove=@AR)"
                                Dim ClearPreviousRecords As New SqlCommand(queryString, connection)
                                ClearPreviousRecords.Parameters.Add("@Tag", SqlDbType.NVarChar)
                                ClearPreviousRecords.Parameters("@Tag").Value = MyRowView("keytag")
                                ClearPreviousRecords.Parameters.Add("@AU", SqlDbType.Int)
                                ClearPreviousRecords.Parameters("@AU").Value = StorageUnit
                                ClearPreviousRecords.Parameters.Add("@AR", SqlDbType.NVarChar)
                                ClearPreviousRecords.Parameters("@AR").Value = "Add"
                                ClearPreviousRecords.ExecuteNonQuery()
    
                                queryString = "INSERT INTO AllTags(KeyTag,AddRemove,AdminUnit) " & _
                                              "VALUES(@Tag,@AR,@AU)"
                                Dim StoreNewTag As New SqlCommand(queryString, connection)
                                StoreNewTag.Parameters.Add("@Tag", SqlDbType.NVarChar)
                                StoreNewTag.Parameters("@Tag").Value = MyRowView("keytag")
                                StoreNewTag.Parameters.Add("@AR", SqlDbType.NVarChar)
                                StoreNewTag.Parameters("@AR").Value = "Add"
                                StoreNewTag.Parameters.Add("@AU", SqlDbType.Int)
                                StoreNewTag.Parameters("@AU").Value = StorageUnit
                                StoreNewTag.ExecuteNonQuery()
    
    
    
                            End If
    
    
                        ElseIf MyRowView("AddRemove") = "Remove" Then
    
                            queryString = "DELETE FROM AllTags " & _
                                          "WHERE (KeyTag=@Tag) AND (AdminUnit=@AU) AND (AddRemove=@AR)"
                            Dim ClearOldRecords As New SqlCommand(queryString, connection)
                            ClearOldRecords.Parameters.Add("@Tag", SqlDbType.NVarChar)
                            ClearOldRecords.Parameters("@Tag").Value = MyRowView("KeyTag")
                            ClearOldRecords.Parameters.Add("@AR", SqlDbType.NVarChar)
                            ClearOldRecords.Parameters("@AR").Value = "Remove"
                            ClearOldRecords.Parameters.Add("@AU", SqlDbType.Int)
                            ClearOldRecords.Parameters("@AU").Value = StorageUnit
                            ClearOldRecords.ExecuteNonQuery()
    
                            queryString = "INSERT INTO AllTags(KeyTag,AddRemove,AdminUnit) " & _
                                          "VALUES(@Tag,@AR,@AU)"
                            Dim StoreNewTag As New SqlCommand(queryString, connection)
                            StoreNewTag.Parameters.Add("@Tag", SqlDbType.NVarChar)
                            StoreNewTag.Parameters("@Tag").Value = MyRowView("keytag")
                            StoreNewTag.Parameters.Add("@AR", SqlDbType.NVarChar)
                            StoreNewTag.Parameters("@AR").Value = "Remove"
                            StoreNewTag.Parameters.Add("@AU", SqlDbType.Int)
                            StoreNewTag.Parameters("@AU").Value = StorageUnit
                            StoreNewTag.ExecuteNonQuery()
    
    
    
    
                        End If
                    End If
                End If
            End Using
        End Sub
    
        Protected Sub SenderAndCCTargetExternalEntities_ServerValidate(source As Object, args As ServerValidateEventArgs) Handles SenderAndCCTargetExternalEntities.ServerValidate
            Dim CCTargetUnits As SqlDataReader
            Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
            Using connection As New SqlConnection(conString)
                Dim queryString As String
                connection.Open()
    
                queryString = "SELECT Indx FROM CCTargetUnits WHERE (LoadedByUserName=@UN)"
                Dim BuildCCTargetUnits As New SqlCommand(queryString, connection)
                BuildCCTargetUnits.Parameters.Add("@UN", SqlDbType.NVarChar)
                BuildCCTargetUnits.Parameters("@UN").Value = Session("UserName")
                CCTargetUnits = BuildCCTargetUnits.ExecuteReader()
    
                If CCTargetUnits.HasRows Then
                    Do While CCTargetUnits.Read()
                        If IsDBNull(CCTargetUnits(0)) = False Then
                            If TDClass.CheckIfExternal(SourceName.SelectedValue) = 1 Then
                                If TDClass.CheckIfExternal(CCTargetUnits(0)) = 1 Then
                                    args.IsValid = False
                                End If
                            End If
                        End If
                    Loop
                End If
    
            End Using
        End Sub
    
        Public Sub SetTargetAsLoggingUserUnits()
    
            Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
            Using connection As New SqlConnection(conString)
    
                connection.Open()
    
                Dim queryString As String = "DELETE FROM NewToTargets WHERE (LoadedByUserName = @UN)"
                Dim RemoveToTargetQuery As New SqlCommand(queryString, connection)
                RemoveToTargetQuery.Parameters.Add("@UN", SqlDbType.NVarChar)
                RemoveToTargetQuery.Parameters("@UN").Value = UserName
                RemoveToTargetQuery.ExecuteNonQuery()
    
                queryString = "SELECT Indx FROM Employees WHERE (UserName=@UN)"
                Dim LoginUserIndxSelectCommand As New SqlCommand(queryString, connection)
                LoginUserIndxSelectCommand.Parameters.Add("@UN", SqlDbType.NVarChar)
                LoginUserIndxSelectCommand.Parameters("@UN").Value = UserName
                Dim LoginUserIndx = LoginUserIndxSelectCommand.ExecuteScalar()
                UserIndx = LoginUserIndx
    
                queryString = "INSERT INTO NewFromTargets(Indx,LoadedByUserName) " &
                              "SELECT DISTINCT UnitsHeads.UnitIndx,@UN " &
                              "FROM AdministrationUnits INNER JOIN UnitsHeads ON AdministrationUnits.Indx = UnitsHeads.UnitIndx " &
                              "WHERE (HeadIndx=@LoginUserIndx) And (CAST(GETDATE() AS DateTime) BETWEEN UnitsHeads.Since And UnitsHeads.Until) And (CAST(GETDATE() AS DateTime) BETWEEN AdministrationUnits.FromDate And AdministrationUnits.ToDate)"
                Dim LoginUserUnitSelectCommand As New SqlCommand(queryString, connection)
                LoginUserUnitSelectCommand.Parameters.Add("@LoginUserIndx", SqlDbType.Int)
                LoginUserUnitSelectCommand.Parameters("@LoginUserIndx").Value = UserIndx
                LoginUserUnitSelectCommand.Parameters.Add("@UN", SqlDbType.NVarChar)
                LoginUserUnitSelectCommand.Parameters("@UN").Value = UserName
                LoginUserUnitSelectCommand.ExecuteNonQuery()
    
            End Using
        End Sub
    
        Public Shared Sub PreparePrivateAllUsers(UserName As String)
    
            Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
            Using connection As New SqlConnection(conString)
                connection.Open()
    
                Dim queryString As String
    
                queryString = "SELECT Indx FROM Employees WHERE (UserName=@UN)"
                Dim GetLoggingUserIndx As New SqlCommand(queryString, connection)
                GetLoggingUserIndx.Parameters.Add("@UN", SqlDbType.NVarChar)
                GetLoggingUserIndx.Parameters("@UN").Value = UserName
                LoggingUserIndx = GetLoggingUserIndx.ExecuteScalar
    
                queryString = "SELECT Name FROM Employees WHERE (UserName=@UN)"
                Dim GetLoggingUserName As New SqlCommand(queryString, connection)
                GetLoggingUserName.Parameters.Add("@UN", SqlDbType.NVarChar)
                GetLoggingUserName.Parameters("@UN").Value = UserName
                Dim LoggingUserName As String = GetLoggingUserName.ExecuteScalar
    
                queryString = "DELETE FROM PrivateAllUsers WHERE (LoadedByUserName=@UN)"
                Dim DelCommand As New SqlCommand(queryString, connection)
                DelCommand.Parameters.Add("@UN", SqlDbType.NVarChar)
                DelCommand.Parameters("@UN").Value = UserName
                DelCommand.ExecuteNonQuery()
    
                queryString = "DELETE FROM PrivateAuthorizedUsers WHERE (LoadedByUserName=@UN)"
                Dim DelCommand1 As New SqlCommand(queryString, connection)
                DelCommand1.Parameters.Add("@UN", SqlDbType.NVarChar)
                DelCommand1.Parameters("@UN").Value = UserName
                DelCommand1.ExecuteNonQuery()
    
    
                queryString = "INSERT INTO PrivateAllUsers(Indx,Name,LoadedByUserName) " & _
                              "SELECT DISTINCT Indx,Name,@UN " & _
                              "FROM Employees " & _
                              "WHERE (UserName <> @UN)"
                Dim LoadPrivateAllUsers As New SqlCommand(queryString, connection)
                LoadPrivateAllUsers.Parameters.Add("@UN", SqlDbType.NVarChar)
                LoadPrivateAllUsers.Parameters("@UN").Value = UserName
                LoadPrivateAllUsers.ExecuteNonQuery()
    
                queryString = "INSERT INTO PrivateAuthorizedUsers(Indx,Name,LoadedByUserName) " & _
                              "VALUES(@Ix,@Name,@UN)"
                Dim LoadLoggingUserAsPrivateAuthUser As New SqlCommand(queryString, connection)
                LoadLoggingUserAsPrivateAuthUser.Parameters.Add("@UN", SqlDbType.NVarChar)
                LoadLoggingUserAsPrivateAuthUser.Parameters("@UN").Value = UserName
                LoadLoggingUserAsPrivateAuthUser.Parameters.Add("@Ix", SqlDbType.Int)
                LoadLoggingUserAsPrivateAuthUser.Parameters("@Ix").Value = LoggingUserIndx
                LoadLoggingUserAsPrivateAuthUser.Parameters.Add("@Name", SqlDbType.NVarChar)
                LoadLoggingUserAsPrivateAuthUser.Parameters("@Name").Value = LoggingUserName
                LoadLoggingUserAsPrivateAuthUser.ExecuteNonQuery()
    
            End Using
    
        End Sub
    
        Protected Sub PrivateUsers_Click(sender As Object, e As EventArgs) Handles PrivateUsers.Click
            Response.Write("<script>")
            Response.Write("window.open('PrivacyPersons.aspx','_blank')")
            Response.Write("</script>")
        End Sub
    
    
        
    
        Public Sub StorePrivatePostingsRecords(ByRef UserName As String)
            Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
            Using connection As New SqlConnection(conString)
    
                connection.Open()
    
                Dim queryString As String = "DELETE FROM PrivatePostings WHERE (LetterID=@LID)"
                Dim RemoveOldLetterRecords As New SqlCommand(queryString, connection)
                RemoveOldLetterRecords.Parameters.Add("@LID", SqlDbType.NVarChar)
                RemoveOldLetterRecords.Parameters("@LID").Value = LetterIDTxtBox.Text
                RemoveOldLetterRecords.ExecuteNonQuery()
    
                queryString = "INSERT INTO PrivatePostings(UserIndx,LetterID) SELECT Indx,@LID FROM PrivateAuthorizedUsers WHERE (LoadedByUserName=@UN)"
                Dim PushPostingPrivacyRecs As New SqlCommand(queryString, connection)
                PushPostingPrivacyRecs.Parameters.Add("@LID", SqlDbType.NVarChar)
                PushPostingPrivacyRecs.Parameters("@LID").Value = LetterIDTxtBox.Text
                PushPostingPrivacyRecs.Parameters.Add("@UN", SqlDbType.NVarChar)
                PushPostingPrivacyRecs.Parameters("@UN").Value = UserName
                PushPostingPrivacyRecs.ExecuteNonQuery()
    
                queryString = "UPDATE Postings SET TopPrivate=@PvtFlag WHERE (RefNo=@RNo)"
                Dim CheckPrivatePostsFlags As New SqlCommand(queryString, connection)
                CheckPrivatePostsFlags.Parameters.Add("@PvtFlag", SqlDbType.Int)
                CheckPrivatePostsFlags.Parameters("@PvtFlag").Value = 1
                CheckPrivatePostsFlags.Parameters.Add("@RNo", SqlDbType.NVarChar)
                CheckPrivatePostsFlags.Parameters("@RNo").Value = Trim(LetterIDTxtBox.Text)
                CheckPrivatePostsFlags.ExecuteNonQuery()
    
            End Using
        End Sub
    
        Public Sub ClearIncomingInfo(ByVal UserName As String)
    
            Dim queryString As String
            Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
            Using connection As New SqlConnection(conString)
                connection.Open()
    
                queryString = "DELETE FROM IncomingLetterInfo WHERE (LoadedByUserIndx=@Ix)"
                Dim RemoveOldIncomingLetterInfo As New SqlCommand(queryString, connection)
                RemoveOldIncomingLetterInfo.Parameters.Add("@Ix", SqlDbType.Int)
                RemoveOldIncomingLetterInfo.Parameters("@Ix").Value = TDClass.GetLoggingUserIndxValue(UserName)
                RemoveOldIncomingLetterInfo.ExecuteNonQuery()
    
    
            End Using
    
        End Sub
    
        Protected Sub IncomingInfoValidator_ServerValidate(source As Object, args As ServerValidateEventArgs) Handles IncomingInfoValidator.ServerValidate
    
            If TDClass.CheckIfExternal(SourceName.SelectedValue) = 0 Then
                Dim IsExist As Integer = 0
                Dim queryString As String
                Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
                Using connection As New SqlConnection(conString)
                    connection.Open()
    
                    queryString = "SELECT COUNT(*) FROM IncomingLetterInfo WHERE (LoadedByUserIndx=@Ix)"
                    Dim IncomingInfoExist As New SqlCommand(queryString, connection)
                    IncomingInfoExist.Parameters.Add("@Ix", SqlDbType.Int)
                    IncomingInfoExist.Parameters("@Ix").Value = TDClass.GetLoggingUserIndxValue(UserName)
                    IsExist = IncomingInfoExist.ExecuteScalar()
                End Using
                If IsExist > 0 Then
                    'args.IsValid = False
                End If
            End If
    
        End Sub
    
        Protected Sub OpenIncomingInfoWindow_Click(sender As Object, e As EventArgs) Handles OpenIncomingInfoWindow.Click
            'Response.Write("<script>")
            'Response.Write("window.open('IncomingPostInfo.aspx','_blank')")
            'Response.Write("</script>")
            LoadIncomingPostInfo()
            ModalPopupExtender1.Show()
        End Sub
        Protected Sub NowDate_CheckedChanged(sender As Object, e As EventArgs) Handles NowDate.CheckedChanged
    
            NowDate.Checked = True
            OtherDate.Checked = False
            imgPopup.Enabled = False
            PostDateTxtBox.Enabled = False
    
        End Sub
    
        Protected Sub OtherDate_CheckedChanged(sender As Object, e As EventArgs) Handles OtherDate.CheckedChanged
    
            NowDate.Checked = False
            OtherDate.Checked = True
            imgPopup.Enabled = True
            PostDateTxtBox.Enabled = True
    
        End Sub
    
        Protected Sub IsTopSecret_CheckedChanged(sender As Object, e As EventArgs) Handles IsTopSecret.CheckedChanged
            If IsTopSecret.Checked = True Then
                PrivateUsers.Enabled = True
            Else
                PrivateUsers.Enabled = False
            End If
        End Sub
    
        Public Sub ClearNewPostingLetter()
    
            Dim queryString As String
            Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
            Using connection As New SqlConnection(conString)
                connection.Open()
    
                queryString = "SELECT COUNT(*) FROM NewPosting WHERE (LetterID=@LID) AND (DraftSavingTime is not Null)"
                Dim CheckIfSentPostWasDraft As New SqlCommand(queryString, connection)
                CheckIfSentPostWasDraft.Parameters.Add("@LID", SqlDbType.NVarChar)
                CheckIfSentPostWasDraft.Parameters("@LID").Value = LetterIDTxtBox.Text
                Dim WasDraft As Integer = CheckIfSentPostWasDraft.ExecuteScalar
    
                If WasDraft > 0 Then
    
                    queryString = "UPDATE NewPosting SET Status=@Sts WHERE (LetterID=@LID) AND (DraftSavingTime is not Null)"
                    Dim UpdateNewPostDraftStatus As New SqlCommand(queryString, connection)
                    UpdateNewPostDraftStatus.Parameters.Add("@LID", SqlDbType.NVarChar)
                    UpdateNewPostDraftStatus.Parameters("@LID").Value = LetterIDPublic
                    UpdateNewPostDraftStatus.Parameters.Add("@Sts", SqlDbType.NVarChar)
                    UpdateNewPostDraftStatus.Parameters("@Sts").Value = "مستخدم"
                    UpdateNewPostDraftStatus.ExecuteNonQuery()
    
                    'Transfer the record into the NewPostingDraftDeletedPosts 
                    queryString = "DELETE FROM NewPostingDraftDeletedPosts WHERE (LetterID=@LID)"
                    Dim ClearOldRecord As New SqlCommand(queryString, connection)
                    ClearOldRecord.Parameters.Add("@LID", SqlDbType.NVarChar)
                    ClearOldRecord.Parameters("@LID").Value = LetterIDTxtBox.Text
                    ClearOldRecord.ExecuteNonQuery()
    
                    queryString = "INSERT INTO NewPostingDraftDeletedPosts " & _
                                  "(RefNo, LetterID, Source, SourceName, Target, TargetName, PostTime, PostType, Importance, RequiredAnsPeriod, Subject, Attachments, ActionAgainstLetter, SubmittedBy, ReceivedBy, Comments, LoadedByUserName, LoggingUserName, LoggingTime, TopPrivate, LoadingUnitIndx, IncomePostDate, IncomeRefNo, DraftNowEntryDate, DraftOtherDateDayVal, DraftOtherDateMonthVal, DraftOtherDateYearVal,DraftPostTypeValue, DraftImportance, DraftRAP, DraftTopPrivate, DraftSavingTime, Status, CreatingIndx, LastSavingUserIndx, DraftDeletedBy, UsingTime) " & _
                                  "SELECT DISTINCT RefNo, LetterID, Source, SourceName, Target, TargetName, PostTime, PostType, Importance, RequiredAnsPeriod, Subject, Attachments, ActionAgainstLetter, SubmittedBy, ReceivedBy, Comments, LoadedByUserName, LoggingUserName, LoggingTime, TopPrivate, LoadingUnitIndx, IncomePostDate, IncomeRefNo, DraftNowEntryDate, DraftOtherDateDayVal, DraftOtherDateMonthVal, DraftOtherDateYearVal, DraftPostTypeValue, DraftImportance, DraftRAP, DraftTopPrivate, DraftSavingTime, Status, CreatingIndx, LastSavingUserIndx,@UI,@UseTime " & _
                                  "FROM NewPosting " & _
                                  "WHERE (LetterID=@LID)"
                    Dim TransferNewPosting As New SqlCommand(queryString, connection)
                    TransferNewPosting.Parameters.Add("@LID", SqlDbType.NVarChar)
                    TransferNewPosting.Parameters("@LID").Value = LetterIDTxtBox.Text
                    TransferNewPosting.Parameters.Add("@UI", SqlDbType.Int)
                    TransferNewPosting.Parameters("@UI").Value = UserIndx
                    TransferNewPosting.Parameters.Add("@UseTime", SqlDbType.DateTime)
                    TransferNewPosting.Parameters("@UseTime").Value = Now().ToString
                    TransferNewPosting.ExecuteNonQuery()
    
                    queryString = "DELETE FROM NewPosting WHERE (LetterID=@LID) AND (DraftSavingTime is not Null)"
                    Dim CleartheRecordFromNewPosting As New SqlCommand(queryString, connection)
                    CleartheRecordFromNewPosting.Parameters.Add("@LID", SqlDbType.NVarChar)
                    CleartheRecordFromNewPosting.Parameters("@LID").Value = LetterIDTxtBox.Text
                    CleartheRecordFromNewPosting.ExecuteNonQuery()
    
                End If
    
            End Using
    
        End Sub
    
        Protected Sub SaveAsDraft_Click(sender As Object, e As EventArgs) Handles SaveAsDraft.Click
    
    
            DontValidate = 1
    
    
            If Page.IsValid = True Then
    
                Dim queryString As String
                Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
                Using connection As New SqlConnection(conString)
    
                    connection.Open()
    
    
                    If TDClass.IsExternal(SourceName.SelectedValue) = 0 Then
                        UserUnitIndx = SourceName.SelectedValue
                    Else
                        UserUnitIndx = TargetName.SelectedValue
                    End If
    
    
                    If Session("DraftChangeLetterIDMade") = 1 Then
                        queryString = "UPDATE NewPosting SET LetterID=@NewLID, " &
                                      "FollowUpID=@FID, " &
                                      "Source=@SRC,Target=@TGT,Subject=@SBJ,Comments=@Cmt,DraftSavingTime=@PTime,DraftPostTypeValue=@PTypeVal,DraftAloneCB=@AloneCB,DraftMultiCB=@MultiCB,DraftNowEntryDate=@NowEntrDate,DraftOtherDateVal=@EntryPostDate, " &
                                      "DraftRAP=@DraftRAP,DraftImportance=@DraftImport,DraftTopPrivate=@DraftTopPrivate,LoadedByUserName=@UN,LoadingUnitIndx=@UnitIx " &
                                      "WHERE (LetterID=@PrevLID)"
                        Dim UpdateNewPostDraft As New SqlCommand(queryString, connection)
                        UpdateNewPostDraft.Parameters.Add("@PrevLID", SqlDbType.NVarChar)
                        UpdateNewPostDraft.Parameters("@PrevLID").Value = Session("DraftChangeLetterIDPrev")
                        UpdateNewPostDraft.Parameters.Add("@NewLID", SqlDbType.NVarChar)
                        UpdateNewPostDraft.Parameters("@NewLID").Value = Session("DraftChangeLetterIDValue")
                        UpdateNewPostDraft.Parameters.Add("@FID", SqlDbType.NVarChar)
                        UpdateNewPostDraft.Parameters("@FID").Value = FollowUpID.Text
                        UpdateNewPostDraft.Parameters.Add("@SRC", SqlDbType.Int)
                        UpdateNewPostDraft.Parameters("@SRC").Value = SourceName.SelectedValue
                        UpdateNewPostDraft.Parameters.Add("@TGT", SqlDbType.Int)
                        UpdateNewPostDraft.Parameters("@TGT").Value = TargetName.SelectedValue
                        UpdateNewPostDraft.Parameters.Add("@SBJ", SqlDbType.NVarChar)
                        UpdateNewPostDraft.Parameters("@SBJ").Value = SubjectTxtBox.Text
                        UpdateNewPostDraft.Parameters.Add("@Cmt", SqlDbType.NVarChar)
                        UpdateNewPostDraft.Parameters("@Cmt").Value = CommentsTxtBox.Text
                        UpdateNewPostDraft.Parameters.Add("@PTime", SqlDbType.DateTime)
                        UpdateNewPostDraft.Parameters("@PTime").Value = Now()
                        UpdateNewPostDraft.Parameters.Add("@PTypeVal", SqlDbType.NVarChar)
                        UpdateNewPostDraft.Parameters("@PTypeVal").Value = PostTypeDDL.SelectedValue
                        UpdateNewPostDraft.Parameters.Add("@AloneCB", SqlDbType.NVarChar)
                        UpdateNewPostDraft.Parameters.Add("@MultiCB", SqlDbType.NVarChar)
                        UpdateNewPostDraft.Parameters.Add("@NowEntrDate", SqlDbType.NVarChar)
                        UpdateNewPostDraft.Parameters.Add("@EntryPostDate", SqlDbType.Date)
                        If AloneCB.Checked = True Then
                            UpdateNewPostDraft.Parameters("@AloneCB").Value = "true"
                            UpdateNewPostDraft.Parameters("@MultiCB").Value = "false"
                        ElseIf MultiCB.Checked = True Then
                            UpdateNewPostDraft.Parameters("@AloneCB").Value = "false"
                            UpdateNewPostDraft.Parameters("@MultiCB").Value = "true"
                        End If
                        If NowDate.Checked = True Then
                            UpdateNewPostDraft.Parameters("@NowEntrDate").Value = "true"
                            UpdateNewPostDraft.Parameters("@EntryPostDate").Value = PostDateTxtBox.Text
                        ElseIf OtherDate.Checked = True Then
                            UpdateNewPostDraft.Parameters("@NowEntrDate").Value = "false"
                            UpdateNewPostDraft.Parameters("@EntryPostDate").Value = PostDateTxtBox.Text
                        End If
                        UpdateNewPostDraft.Parameters.Add("@DraftRAP", SqlDbType.Int)
                        UpdateNewPostDraft.Parameters.Add("@DraftImport", SqlDbType.NVarChar)
                        UpdateNewPostDraft.Parameters.Add("@DraftTopPrivate", SqlDbType.Int)
                        If PostTypeDDL.Text = "طلب" Then
                            UpdateNewPostDraft.Parameters("@DraftRAP").Value = CInt(RAPTxtBox.Text)
                        Else
                            UpdateNewPostDraft.Parameters("@DraftRAP").Value = 0
                        End If
                        UpdateNewPostDraft.Parameters("@DraftImport").Value = ImportanceDD.SelectedValue
                        If IsTopSecret.Checked = True Then
                            UpdateNewPostDraft.Parameters("@DraftTopPrivate").Value = 1
                        Else
                            UpdateNewPostDraft.Parameters("@DraftTopPrivate").Value = 0
                        End If
                        UpdateNewPostDraft.Parameters.Add("@UN", SqlDbType.NVarChar)
                        UpdateNewPostDraft.Parameters("@UN").Value = UserName
                        UpdateNewPostDraft.Parameters.Add("@UnitIx", SqlDbType.Int)
                        UpdateNewPostDraft.Parameters("@UnitIx").Value = UserUnitIndx
                        UpdateNewPostDraft.ExecuteNonQuery()
                        Session("DraftChangeLetterIDMade") = 0
                        GoTo UpdateResume
                    End If
    
                    queryString = "SELECT COUNT(*) FROM NewPosting WHERE (LetterID=@LID) AND (LoadingUnitIndx=@UnitIx)"
                    Dim CheckIfLetterExist As New SqlCommand(queryString, connection)
                    CheckIfLetterExist.Parameters.Add("@LID", SqlDbType.NVarChar)
                    CheckIfLetterExist.Parameters("@LID").Value = LetterIDTxtBox.Text
                    CheckIfLetterExist.Parameters.Add("@UnitIx", SqlDbType.Int)
                    CheckIfLetterExist.Parameters("@UnitIx").Value = UserUnitIndx
                    Dim LetterExist As Integer = CheckIfLetterExist.ExecuteScalar()
    
                    If LetterExist = 0 Then
                        queryString = "INSERT INTO NewPosting(LetterID,FollowUpID,Source,Target,Subject,Comments,DraftSavingTime,DraftPostTypeValue,DraftAloneCB,DraftMultiCB,DraftNowEntryDate,DraftOtherDateVal,DraftRAP,DraftImportance,DraftTopPrivate,LoadedByUserName,LoadingUnitIndx,CreatingIndx,LastSavingUserIndx) " &
                                      "VALUES (@LID,@FID,@SRC,@TGT,@SBJ,@Cmt,@PTime,@PTypeVal,@AloneCB,@MultiCB,@NowEntrDate,@EntryPostDate,@DraftRAP,@DraftImport,@DraftTopPrivate,@UN,@UnitIx,@CreatingUnitIndx,@LastUpdatingUser)"
                        Dim AddNewPostDraft As New SqlCommand(queryString, connection)
                        AddNewPostDraft.Parameters.Add("@LID", SqlDbType.NVarChar)
                        AddNewPostDraft.Parameters("@LID").Value = LetterIDTxtBox.Text
                        AddNewPostDraft.Parameters.Add("@FID", SqlDbType.NVarChar)
                        AddNewPostDraft.Parameters("@FID").Value = FollowUpID.Text
                        AddNewPostDraft.Parameters.Add("@SRC", SqlDbType.Int)
                        AddNewPostDraft.Parameters("@SRC").Value = SourceName.SelectedValue
                        AddNewPostDraft.Parameters.Add("@TGT", SqlDbType.Int)
                        AddNewPostDraft.Parameters("@TGT").Value = TargetName.SelectedValue
                        AddNewPostDraft.Parameters.Add("@SBJ", SqlDbType.NVarChar)
                        AddNewPostDraft.Parameters("@SBJ").Value = SubjectTxtBox.Text
                        AddNewPostDraft.Parameters.Add("@Cmt", SqlDbType.NVarChar)
                        AddNewPostDraft.Parameters("@Cmt").Value = CommentsTxtBox.Text
                        AddNewPostDraft.Parameters.Add("@PTime", SqlDbType.DateTime)
                        AddNewPostDraft.Parameters("@PTime").Value = Now()
                        AddNewPostDraft.Parameters.Add("@PTypeVal", SqlDbType.NVarChar)
                        AddNewPostDraft.Parameters("@PTypeVal").Value = PostTypeDDL.SelectedValue
                        AddNewPostDraft.Parameters.Add("@AloneCB", SqlDbType.NVarChar)
                        AddNewPostDraft.Parameters.Add("@MultiCB", SqlDbType.NVarChar)
                        AddNewPostDraft.Parameters.Add("@NowEntrDate", SqlDbType.NVarChar)
                        AddNewPostDraft.Parameters.Add("@EntryPostDate", SqlDbType.Date)
                        If AloneCB.Checked = True Then
                            AddNewPostDraft.Parameters("@AloneCB").Value = "true"
                            AddNewPostDraft.Parameters("@MultiCB").Value = "false"
                        ElseIf MultiCB.Checked = True Then
                            AddNewPostDraft.Parameters("@AloneCB").Value = "false"
                            AddNewPostDraft.Parameters("@MultiCB").Value = "true"
                        End If
                        If NowDate.Checked = True Then
                            AddNewPostDraft.Parameters("@NowEntrDate").Value = "true"
                            AddNewPostDraft.Parameters("@EntryPostDate").Value = PostDateTxtBox.Text
                        ElseIf OtherDate.Checked = True Then
                            AddNewPostDraft.Parameters("@NowEntrDate").Value = "false"
                            AddNewPostDraft.Parameters("@EntryPostDate").Value = PostDateTxtBox.Text
                        End If
                        AddNewPostDraft.Parameters.Add("@DraftRAP", SqlDbType.Int)
                        AddNewPostDraft.Parameters.Add("@DraftImport", SqlDbType.NVarChar)
                        AddNewPostDraft.Parameters.Add("@DraftTopPrivate", SqlDbType.Int)
                        If PostTypeDDL.Text = "طلب" Then
                            AddNewPostDraft.Parameters("@DraftRAP").Value = CInt(RAPTxtBox.Text)
                        Else
                            AddNewPostDraft.Parameters("@DraftRAP").Value = 0
                        End If
                        AddNewPostDraft.Parameters("@DraftImport").Value = ImportanceDD.SelectedValue
                        If IsTopSecret.Checked = True Then
                            AddNewPostDraft.Parameters("@DraftTopPrivate").Value = 1
                        Else
                            AddNewPostDraft.Parameters("@DraftTopPrivate").Value = 0
                        End If
                        AddNewPostDraft.Parameters.Add("@UN", SqlDbType.NVarChar)
                        AddNewPostDraft.Parameters("@UN").Value = UserName
                        AddNewPostDraft.Parameters.Add("@UnitIx", SqlDbType.Int)
                        AddNewPostDraft.Parameters("@UnitIx").Value = UserUnitIndx
                        AddNewPostDraft.Parameters.Add("@CreatingUnitIndx", SqlDbType.Int)
                        AddNewPostDraft.Parameters("@CreatingUnitIndx").Value = UserUnitIndx
                        AddNewPostDraft.Parameters.Add("@LastUpdatingUser", SqlDbType.Int)
                        AddNewPostDraft.Parameters("@LastUpdatingUser").Value = UserIndx
                        AddNewPostDraft.ExecuteNonQuery()
                    Else
                        queryString = "UPDATE NewPosting " &
                                      "SET FollowUpID,Source=@SRC,Target=@TGT,Subject=@SBJ,Comments=@Cmt,DraftSavingTime=@PTime,DraftPostTypeValue=@PTypeVal,DraftAloneCB=@AloneCB,DraftMultiCB=@MultiCB,DraftNowEntryDate=@NowEntrDate,DraftOtherDateVal=@EntryPostDate,DraftRAP=@DraftRAP,DraftImportance=@DraftImport,DraftTopPrivate=@DraftTopPrivate,LoadedByUserName=@UN,LoadingUnitIndx=@UnitIx,LastSavingUserIndx=@LastUpdatingUser " &
                                      "WHERE (LetterID=@LID)"
                        Dim UpdateNewPostDraft As New SqlCommand(queryString, connection)
                        UpdateNewPostDraft.Parameters.Add("@LID", SqlDbType.NVarChar)
                        UpdateNewPostDraft.Parameters("@LID").Value = LetterIDTxtBox.Text
                        UpdateNewPostDraft.Parameters.Add("@FID", SqlDbType.NVarChar)
                        UpdateNewPostDraft.Parameters("@FID").Value = FollowUpID.Text
                        UpdateNewPostDraft.Parameters.Add("@SRC", SqlDbType.Int)
                        UpdateNewPostDraft.Parameters("@SRC").Value = SourceName.SelectedValue
                        UpdateNewPostDraft.Parameters.Add("@TGT", SqlDbType.Int)
                        UpdateNewPostDraft.Parameters("@TGT").Value = TargetName.SelectedValue
                        UpdateNewPostDraft.Parameters.Add("@SBJ", SqlDbType.NVarChar)
                        UpdateNewPostDraft.Parameters("@SBJ").Value = SubjectTxtBox.Text
                        UpdateNewPostDraft.Parameters.Add("@Cmt", SqlDbType.NVarChar)
                        UpdateNewPostDraft.Parameters("@Cmt").Value = CommentsTxtBox.Text
                        UpdateNewPostDraft.Parameters.Add("@PTime", SqlDbType.DateTime)
                        UpdateNewPostDraft.Parameters("@PTime").Value = Now()
                        UpdateNewPostDraft.Parameters.Add("@PTypeVal", SqlDbType.NVarChar)
                        UpdateNewPostDraft.Parameters("@PTypeVal").Value = PostTypeDDL.SelectedValue
                        UpdateNewPostDraft.Parameters.Add("@AloneCB", SqlDbType.NVarChar)
                        UpdateNewPostDraft.Parameters.Add("@MultiCB", SqlDbType.NVarChar)
                        UpdateNewPostDraft.Parameters.Add("@NowEntrDate", SqlDbType.NVarChar)
                        UpdateNewPostDraft.Parameters.Add("@EntryPostDate", SqlDbType.NVarChar)
                        If AloneCB.Checked = True Then
                            UpdateNewPostDraft.Parameters("@AloneCB").Value = "true"
                            UpdateNewPostDraft.Parameters("@MultiCB").Value = "false"
                        ElseIf MultiCB.Checked = True Then
                            UpdateNewPostDraft.Parameters("@AloneCB").Value = "false"
                            UpdateNewPostDraft.Parameters("@MultiCB").Value = "true"
                        End If
                        If NowDate.Checked = True Then
                            UpdateNewPostDraft.Parameters("@NowEntrDate").Value = "true"
                            UpdateNewPostDraft.Parameters("@EntryPostDate").Value = PostDateTxtBox.Text
                        ElseIf OtherDate.Checked = True Then
                            UpdateNewPostDraft.Parameters("@NowEntrDate").Value = "false"
                            UpdateNewPostDraft.Parameters("@EntryPostDate").Value = PostDateTxtBox.Text
                        End If
                        UpdateNewPostDraft.Parameters.Add("@DraftRAP", SqlDbType.Int)
                        UpdateNewPostDraft.Parameters.Add("@DraftImport", SqlDbType.NVarChar)
                        UpdateNewPostDraft.Parameters.Add("@DraftTopPrivate", SqlDbType.Int)
                        If PostTypeDDL.Text = "طلب" Then
                            UpdateNewPostDraft.Parameters("@DraftRAP").Value = CInt(RAPTxtBox.Text)
                        Else
                            UpdateNewPostDraft.Parameters("@DraftRAP").Value = 0
                        End If
                        UpdateNewPostDraft.Parameters("@DraftImport").Value = ImportanceDD.SelectedValue
                        If IsTopSecret.Checked = True Then
                            UpdateNewPostDraft.Parameters("@DraftTopPrivate").Value = 1
                        Else
                            UpdateNewPostDraft.Parameters("@DraftTopPrivate").Value = 0
                        End If
                        UpdateNewPostDraft.Parameters.Add("@UN", SqlDbType.NVarChar)
                        UpdateNewPostDraft.Parameters("@UN").Value = UserName
                        UpdateNewPostDraft.Parameters.Add("@UnitIx", SqlDbType.Int)
                        UpdateNewPostDraft.Parameters("@UnitIx").Value = UserUnitIndx
                        UpdateNewPostDraft.Parameters.Add("@LastUpdatingUser", SqlDbType.Int)
                        UpdateNewPostDraft.Parameters("@LastUpdatingUser").Value = UserIndx
                        UpdateNewPostDraft.ExecuteNonQuery()
                    End If
    
    UpdateResume:
                    queryString = "UPDATE NewPosting SET SourceName = ExternalEntities.Name FROM NewPosting INNER JOIN ExternalEntities ON NewPosting.Source = ExternalEntities.Indx"
                    Dim UpdateCommand1 As New SqlCommand(queryString, connection)
                    UpdateCommand1.ExecuteNonQuery()
    
                    queryString = "UPDATE NewPosting SET TargetName = ExternalEntities.Name FROM NewPosting INNER JOIN ExternalEntities ON NewPosting.Target = ExternalEntities.Indx"
                    Dim UpdateCommand2 As New SqlCommand(queryString, connection)
                    UpdateCommand2.ExecuteNonQuery()
    
                    queryString = "UPDATE NewPosting SET SourceName = AdministrationUnits.Name FROM AdministrationUnits INNER JOIN NewPosting ON AdministrationUnits.Indx = NewPosting.Source"
                    Dim UpdateCommand3 As New SqlCommand(queryString, connection)
                    UpdateCommand3.ExecuteNonQuery()
    
                    queryString = "UPDATE NewPosting SET TargetName = AdministrationUnits.Name FROM AdministrationUnits INNER JOIN NewPosting ON AdministrationUnits.Indx = NewPosting.Target"
                    Dim UpdateCommand4 As New SqlCommand(queryString, connection)
                    UpdateCommand4.ExecuteNonQuery()
    
                    StoreDraftNewPostMultiTargets()
                    StoreDraftIncomingLetterInfo()
                    StoreDraftTags()
                    StoreDraftCCUnits()
                    StoreDraftPrvteAuthUsers()
                    'Session("activatevalidator") = 1
                    Response.Redirect("~\NewPosting\DraftSaved.aspx")
    
                End Using
    
            End If
    
            PerformValidation = 1
    
        End Sub
    
        Protected Sub OpenDraft_Click(sender As Object, e As EventArgs) Handles OpenDraft.Click
            Response.Redirect("~\NewPosting\NewDraftsList.aspx")
        End Sub
        Public Sub StoreDraftNewPostMultiTargets()
    
            Dim queryString As String
            Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
            Using connection As New SqlConnection(conString)
                connection.Open()
    
                'queryString = "DELETE FROM DraftNewPostTargetUnits WHERE (LetterID=@LID) AND (LoadedByUserName=@UN)"
                queryString = "DELETE FROM DraftNewPostTargetUnits WHERE (LetterID=@LID)"
                Dim RemoveOldRecords As New SqlCommand(queryString, connection)
                RemoveOldRecords.Parameters.Add("@LID", SqlDbType.NVarChar)
                RemoveOldRecords.Parameters("@LID").Value = LetterIDPublic
                RemoveOldRecords.Parameters.Add("@UN", SqlDbType.NVarChar)
                RemoveOldRecords.Parameters("@UN").Value = UserName
                RemoveOldRecords.ExecuteNonQuery()
    
                'queryString = "INSERT INTO DraftNewPostTargetUnits(Indx,Name,LetterID,LoadedByUserName) SELECT DISTINCT Indx,Name,@LID,LoadedByUserName FROM NewPostTargetUnits WHERE (LoadedByUserName=@UN)"
                queryString = "INSERT INTO DraftNewPostTargetUnits(Indx,Name,LetterID) SELECT DISTINCT Indx,Name,@LID FROM NewPostTargetUnits WHERE (LoadedByUserName=@UN)"
                Dim StoreNewPostTargetUnits As New SqlCommand(queryString, connection)
                StoreNewPostTargetUnits.Parameters.Add("@LID", SqlDbType.NVarChar)
                StoreNewPostTargetUnits.Parameters.Add("@UN", SqlDbType.NVarChar)
                StoreNewPostTargetUnits.Parameters("@LID").Value = LetterIDPublic
                StoreNewPostTargetUnits.Parameters("@UN").Value = UserName
                StoreNewPostTargetUnits.ExecuteNonQuery()
    
            End Using
    
        End Sub
        Public Sub StoreDraftIncomingLetterInfo()
    
            Dim queryString As String
            Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
            Using connection As New SqlConnection(conString)
                connection.Open()
    
                'queryString = "DELETE FROM DraftIncomingLetterInfo WHERE (LetterID=@LID) AND (LoadedByUserIndx=@UI)"
                queryString = "DELETE FROM DraftIncomingLetterInfo WHERE (LetterID=@LID)"
                Dim RemoveOldRecords As New SqlCommand(queryString, connection)
                RemoveOldRecords.Parameters.Add("@LID", SqlDbType.NVarChar)
                RemoveOldRecords.Parameters("@LID").Value = LetterIDPublic
                RemoveOldRecords.Parameters.Add("@UI", SqlDbType.Int)
                RemoveOldRecords.Parameters("@UI").Value = UserIndx
                RemoveOldRecords.ExecuteNonQuery()
    
                'queryString = "INSERT INTO DraftIncomingLetterInfo(IncomePostDate,IncomeRefNo,LetterID,LoadedByUserIndx) SELECT DISTINCT IncomePostDate,IncomeRefNo,@LID,LoadedByUserIndx FROM IncomingLetterInfo WHERE (LoadedByUserIndx=@UI)"
                queryString = "INSERT INTO DraftIncomingLetterInfo(IncomePostDate,IncomeRefNo,LetterID) SELECT DISTINCT IncomePostDate,IncomeRefNo,@LID FROM IncomingLetterInfo WHERE (LoadedByUserIndx=@UI)"
                Dim StoreDraftIncomingLetterInfoQry As New SqlCommand(queryString, connection)
                StoreDraftIncomingLetterInfoQry.Parameters.Add("@LID", SqlDbType.NVarChar)
                StoreDraftIncomingLetterInfoQry.Parameters.Add("@UI", SqlDbType.NVarChar)
                StoreDraftIncomingLetterInfoQry.Parameters("@LID").Value = LetterIDPublic
                StoreDraftIncomingLetterInfoQry.Parameters("@UI").Value = UserIndx
                StoreDraftIncomingLetterInfoQry.ExecuteNonQuery()
    
            End Using
    
        End Sub
        Public Sub StoreDraftTags()
    
            Dim queryString As String
            Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
            Using connection As New SqlConnection(conString)
                connection.Open()
    
                'queryString = "DELETE FROM DraftSelectedTags WHERE (LetterID=@LID) AND (LoadedByUserName=@UN)"
                queryString = "DELETE FROM DraftSelectedTags WHERE (LetterID=@LID)"
                Dim RemoveOldRecords1 As New SqlCommand(queryString, connection)
                RemoveOldRecords1.Parameters.Add("@LID", SqlDbType.NVarChar)
                RemoveOldRecords1.Parameters("@LID").Value = LetterIDPublic
                'RemoveOldRecords1.Parameters.Add("@UN", SqlDbType.NVarChar)
                'RemoveOldRecords1.Parameters("@UN").Value = UserName
                RemoveOldRecords1.ExecuteNonQuery()
    
                'queryString = "INSERT INTO DraftSelectedTags(KeyTag,LetterID,LoadedByUserName) SELECT DISTINCT KeyTag,@LID,LoadedByUserName FROM SelectedTags WHERE (LoadedByUserName=@UN)"
                queryString = "INSERT INTO DraftSelectedTags(KeyTag,LetterID) SELECT DISTINCT KeyTag,@LID FROM SelectedTags WHERE (LoadedByUserName=@UN)"
                Dim StoreDraftSelectedTags As New SqlCommand(queryString, connection)
                StoreDraftSelectedTags.Parameters.Add("@LID", SqlDbType.NVarChar)
                StoreDraftSelectedTags.Parameters.Add("@UN", SqlDbType.NVarChar)
                StoreDraftSelectedTags.Parameters("@LID").Value = LetterIDPublic
                StoreDraftSelectedTags.Parameters("@UN").Value = UserName
                StoreDraftSelectedTags.ExecuteNonQuery()
    
                'queryString = "DELETE FROM DraftAllTagsTemp WHERE (LetterID=@LID) AND (LoadedByUserName=@UN)"
                queryString = "DELETE FROM DraftAllTagsTemp WHERE (LetterID=@LID)"
                Dim RemoveOldRecords2 As New SqlCommand(queryString, connection)
                RemoveOldRecords2.Parameters.Add("@LID", SqlDbType.NVarChar)
                RemoveOldRecords2.Parameters("@LID").Value = LetterIDPublic
                'RemoveOldRecords2.Parameters.Add("@UN", SqlDbType.NVarChar)
                'RemoveOldRecords2.Parameters("@UN").Value = UserName
                RemoveOldRecords2.ExecuteNonQuery()
    
                'queryString = "INSERT INTO DraftAllTagsTemp(KeyTag,AddRemove,LetterID,LoadedByUserName) SELECT DISTINCT KeyTag,AddRemove,@LID,LoadedByUserName FROM AllTagsTemp WHERE (LoadedByUserName=@UN)"
                queryString = "INSERT INTO DraftAllTagsTemp(KeyTag,AddRemove,LetterID) SELECT DISTINCT KeyTag,AddRemove,@LID FROM AllTagsTemp WHERE (LoadedByUserName=@UN)"
                Dim StoreDraftAllTagsTemp As New SqlCommand(queryString, connection)
                StoreDraftAllTagsTemp.Parameters.Add("@LID", SqlDbType.NVarChar)
                StoreDraftAllTagsTemp.Parameters.Add("@UN", SqlDbType.NVarChar)
                StoreDraftAllTagsTemp.Parameters("@LID").Value = LetterIDPublic
                StoreDraftAllTagsTemp.Parameters("@UN").Value = UserName
                StoreDraftAllTagsTemp.ExecuteNonQuery()
    
    
                GridView1.DataBind()
    
    
            End Using
    
        End Sub
        Public Sub StoreDraftCCUnits()
    
            Dim queryString As String
            Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
            Using connection As New SqlConnection(conString)
                connection.Open()
    
                'queryString = "DELETE FROM DraftCCTargetUnits WHERE (LetterID=@LID) AND (LoadedByUserName=@UN)"
                queryString = "DELETE FROM DraftCCTargetUnits WHERE (LetterID=@LID)"
                Dim RemoveOldRecords1 As New SqlCommand(queryString, connection)
                RemoveOldRecords1.Parameters.Add("@LID", SqlDbType.NVarChar)
                RemoveOldRecords1.Parameters("@LID").Value = LetterIDPublic
                RemoveOldRecords1.Parameters.Add("@UN", SqlDbType.NVarChar)
                RemoveOldRecords1.Parameters("@UN").Value = UserName
                RemoveOldRecords1.ExecuteNonQuery()
    
                'queryString = "INSERT INTO DraftCCTargetUnits(Indx,Name,LetterID,LoadedByUserName) SELECT Indx,Name,@LID,LoadedByUserName FROM CCTargetUnits WHERE (LoadedByUserName=@UN)"
                queryString = "INSERT INTO DraftCCTargetUnits(Indx,Name,LetterID) SELECT Indx,Name,@LID FROM CCTargetUnits WHERE (LoadedByUserName=@UN)"
                Dim StoreDraftTargetUnits As New SqlCommand(queryString, connection)
                StoreDraftTargetUnits.Parameters.Add("@LID", SqlDbType.NVarChar)
                StoreDraftTargetUnits.Parameters.Add("@UN", SqlDbType.NVarChar)
                StoreDraftTargetUnits.Parameters("@LID").Value = LetterIDPublic
                StoreDraftTargetUnits.Parameters("@UN").Value = UserName
                StoreDraftTargetUnits.ExecuteNonQuery()
    
    
            End Using
    
        End Sub
        Public Sub StoreDraftPrvteAuthUsers()
    
            Dim queryString As String
            Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
            Using connection As New SqlConnection(conString)
                connection.Open()
    
                'queryString = "DELETE FROM DraftPrivateAuthorizedUsers WHERE (LetterID=@LID) AND (LoadedByUserName=@UN)"
                queryString = "DELETE FROM DraftPrivateAuthorizedUsers WHERE (LetterID=@LID)"
                Dim RemoveOldRecords1 As New SqlCommand(queryString, connection)
                RemoveOldRecords1.Parameters.Add("@LID", SqlDbType.NVarChar)
                RemoveOldRecords1.Parameters("@LID").Value = LetterIDPublic
                'RemoveOldRecords1.Parameters.Add("@UN", SqlDbType.NVarChar)
                'RemoveOldRecords1.Parameters("@UN").Value = UserName
                RemoveOldRecords1.ExecuteNonQuery()
    
                'queryString = "INSERT INTO DraftPrivateAuthorizedUsers(Indx,Name,LetterID,LoadedByUserName) SELECT Indx,Name,@LID,LoadedByUserName FROM PrivateAuthorizedUsers WHERE (LoadedByUserName=@UN)"
                queryString = "INSERT INTO DraftPrivateAuthorizedUsers(Indx,Name,LetterID) SELECT Indx,Name,@LID FROM PrivateAuthorizedUsers WHERE (LoadedByUserName=@UN)"
                Dim StoreDraftPrvtAuthUsers As New SqlCommand(queryString, connection)
                StoreDraftPrvtAuthUsers.Parameters.Add("@LID", SqlDbType.NVarChar)
                StoreDraftPrvtAuthUsers.Parameters.Add("@UN", SqlDbType.NVarChar)
                StoreDraftPrvtAuthUsers.Parameters("@LID").Value = LetterIDPublic
                StoreDraftPrvtAuthUsers.Parameters("@UN").Value = UserName
                StoreDraftPrvtAuthUsers.ExecuteNonQuery()
    
    
            End Using
    
        End Sub
    
        Protected Sub EditLetterID_Click(sender As Object, e As EventArgs) Handles EditLetterID.Click
    
            Dim queryString As String
            Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
            Using connection As New SqlConnection(conString)
                connection.Open()
    
                queryString = "SELECT COUNT(*) FROM NewPosting WHERE (LetterID=@LID)"
                Dim CheckIfSaved1 As New SqlCommand(queryString, connection)
                CheckIfSaved1.Parameters.Add("@LID", SqlDbType.NVarChar)
                CheckIfSaved1.Parameters("@LID").Value = LetterIDPublic
                Dim IsSaved1 As Integer = CheckIfSaved1.ExecuteScalar
    
                queryString = "SELECT COUNT(*) FROM Postings WHERE (LetterID=@LID)"
                Dim CheckIfSaved2 As New SqlCommand(queryString, connection)
                CheckIfSaved2.Parameters.Add("@LID", SqlDbType.NVarChar)
                CheckIfSaved2.Parameters("@LID").Value = LetterIDPublic
                Dim IsSaved2 As Integer = CheckIfSaved2.ExecuteScalar
    
                StoreDraftChangeLetterIDIntoSession()
                If IsSaved1 + IsSaved2 > 0 Then
                    Response.Redirect("~\NewPosting\ChangeLetterID.aspx")
                Else
                    Response.Redirect("~\NewPosting\NoLetterIDChanged.aspx")
                End If
    
            End Using
    
        End Sub
    
        Public Sub StoreDraftChangeLetterIDIntoSession()
    
    
            Session("DraftChangeLetterIDSource") = SourceName.SelectedValue
            Session("DraftChangeLetterIDTarget") = TargetName.SelectedValue
    
            Session("DraftChangeLetterIDValue") = LetterIDTxtBox.Text
            Session("DraftChangeFollowUpIDValue") = FollowUpID.Text
    
            If AloneCB.Checked = True Then
                Session("DraftChangeLetterIDAloneCB") = "true"
            ElseIf AloneCB.Checked = False Then
                Session("DraftChangeLetterIDAloneCB") = "false"
            End If
    
            If MultiCB.Checked = True Then
                Session("DraftChangeLetterIDMultiCB") = "true"
            ElseIf MultiCB.Checked = False Then
                Session("DraftChangeLetterIDMultiCB") = "false"
            End If
    
            If NowDate.Checked = True Then
                Session("DraftChangeLetterIDNowDate") = "true"
            Else
                Session("DraftChangeLetterIDNowDate") = "false"
            End If
    
            If IsTopSecret.Checked = True Then
                Session("DraftChangeLetterIDIsTopSecret") = "true"
            Else
                Session("DraftChangeLetterIDIsTopSecret") = "false"
            End If
    
            Session("DraftChangeLetterIDDateVal") = PostDateTxtBox.Text
    
            Session("DraftChangeLetterIDSubject") = SubjectTxtBox.Text
            Session("DraftChangeLetterIDComments") = CommentsTxtBox.Text
            Session("DraftChangeLetterIDTypeDDLValue") = PostTypeDDL.SelectedValue
            If PostTypeDDL.SelectedValue = "طلب" Then
                Session("DraftChangeLetterIDRAP") = CInt(RAPTxtBox.Text)
            End If
            Session("DraftChangeLetterIDImportanceValue") = ImportanceDD.SelectedValue
    
        End Sub
    
      
    
        Public Sub RemoveDeletedLetterRecordsFromDraftTables(ByVal LetterID As String)
            RemoveDeletedLetterRecordsfromDraftAllTagsTemp(LetterID)
            RemoveDeletedLetterRecordsfromDraftCCTargetUnits(LetterID)
            RemoveDeletedLetterRecordsfromDraftIncomingLetterInfo(LetterID)
            RemoveDeletedLetterRecordsfromDraftNewPostTargetUnits(LetterID)
            RemoveDeletedLetterRecordsfromDraftPvtAuthUsers(LetterID)
            RemoveDeletedLetterRecordsfromDraftSelectedTags(LetterID)
        End Sub
        Public Sub RemoveDeletedLetterRecordsfromDraftAllTagsTemp(ByVal LetterID As String)
            Dim queryString As String
            Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
            Using connection As New SqlConnection(conString)
                connection.Open()
    
                queryString = "DELETE FROM DraftAllTagsTemp WHERE (LetterID=@LID)"
                Dim TruncRecords As New SqlCommand(queryString, connection)
                TruncRecords.Parameters.Add("@LID", SqlDbType.NVarChar)
                TruncRecords.Parameters("@LID").Value = LetterID
                TruncRecords.ExecuteNonQuery()
    
            End Using
        End Sub
        Public Sub RemoveDeletedLetterRecordsfromDraftCCTargetUnits(ByVal LetterID As String)
            Dim queryString As String
            Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
            Using connection As New SqlConnection(conString)
                connection.Open()
    
                queryString = "DELETE FROM DraftCCTargetUnits WHERE (LetterID=@LID)"
                Dim TruncRecords As New SqlCommand(queryString, connection)
                TruncRecords.Parameters.Add("@LID", SqlDbType.NVarChar)
                TruncRecords.Parameters("@LID").Value = LetterID
                TruncRecords.ExecuteNonQuery()
    
            End Using
        End Sub
        Public Sub RemoveDeletedLetterRecordsfromDraftIncomingLetterInfo(ByVal LetterID As String)
            Dim queryString As String
            Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
            Using connection As New SqlConnection(conString)
                connection.Open()
    
                queryString = "DELETE FROM DraftIncomingLetterInfo WHERE (LetterID=@LID)"
                Dim TruncRecords As New SqlCommand(queryString, connection)
                TruncRecords.Parameters.Add("@LID", SqlDbType.NVarChar)
                TruncRecords.Parameters("@LID").Value = LetterID
                TruncRecords.ExecuteNonQuery()
    
            End Using
        End Sub
        Public Sub RemoveDeletedLetterRecordsfromDraftNewPostTargetUnits(ByVal LetterID As String)
            Dim queryString As String
            Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
            Using connection As New SqlConnection(conString)
                connection.Open()
    
                queryString = "DELETE FROM DraftNewPostTargetUnits WHERE (LetterID=@LID)"
                Dim TruncRecords As New SqlCommand(queryString, connection)
                TruncRecords.Parameters.Add("@LID", SqlDbType.NVarChar)
                TruncRecords.Parameters("@LID").Value = LetterID
                TruncRecords.ExecuteNonQuery()
    
            End Using
        End Sub
        Public Sub RemoveDeletedLetterRecordsfromDraftPvtAuthUsers(ByVal LetterID As String)
            Dim queryString As String
            Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
            Using connection As New SqlConnection(conString)
                connection.Open()
    
                queryString = "DELETE FROM DraftPrivateAuthorizedUsers WHERE (LetterID=@LID)"
                Dim TruncRecords As New SqlCommand(queryString, connection)
                TruncRecords.Parameters.Add("@LID", SqlDbType.NVarChar)
                TruncRecords.Parameters("@LID").Value = LetterID
                TruncRecords.ExecuteNonQuery()
    
            End Using
        End Sub
        Public Sub RemoveDeletedLetterRecordsfromDraftSelectedTags(ByVal LetterID As String)
            Dim queryString As String
            Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
            Using connection As New SqlConnection(conString)
                connection.Open()
    
                queryString = "DELETE FROM DraftSelectedTags WHERE (LetterID=@LID)"
                Dim TruncRecords As New SqlCommand(queryString, connection)
                TruncRecords.Parameters.Add("@LID", SqlDbType.NVarChar)
                TruncRecords.Parameters("@LID").Value = LetterID
                TruncRecords.ExecuteNonQuery()
    
            End Using
        End Sub
    
        Public Sub AddPrivatePostingsRecords(ByVal LetterID As String)
    
            Dim queryString As String
            Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
            Using connection As New SqlConnection(conString)
                connection.Open()
                queryString = "INSERT INTO PrivatePostings(UserIndx,LetterID) SELECT Indx,@LID FROM PrivateAuthorizedUsers WHERE (LoadedByUserName=@UN)"
                Dim PushPostingPrivacyRecs As New SqlCommand(queryString, connection)
                PushPostingPrivacyRecs.Parameters.Add("@LID", SqlDbType.NVarChar)
                PushPostingPrivacyRecs.Parameters("@LID").Value = LetterID
                PushPostingPrivacyRecs.Parameters.Add("@UN", SqlDbType.NVarChar)
                PushPostingPrivacyRecs.Parameters("@UN").Value = UserName
                PushPostingPrivacyRecs.ExecuteNonQuery()
    
                queryString = "UPDATE Postings SET TopPrivate=@Pvt WHERE (LetterID=@LID)"
                Dim SetPrivateField As New SqlCommand(queryString, connection)
                SetPrivateField.Parameters.Add("@LID", SqlDbType.NVarChar)
                SetPrivateField.Parameters("@LID").Value = LetterID
                SetPrivateField.Parameters.Add("@UN", SqlDbType.NVarChar)
                SetPrivateField.Parameters("@UN").Value = UserName
                If IsTopSecret.Checked = True Then
                    SetPrivateField.Parameters.Add("@Pvt", SqlDbType.Int)
                    SetPrivateField.Parameters("@Pvt").Value = 1
                    SetPrivateField.ExecuteNonQuery()
                Else
                    SetPrivateField.Parameters.Add("@Pvt", SqlDbType.Int)
                    SetPrivateField.Parameters("@Pvt").Value = 0
                    SetPrivateField.ExecuteNonQuery()
                End If
    
            End Using
        End Sub
        Protected Sub AttachmentRequiredFile_ServerValidate(source As Object, args As ServerValidateEventArgs) Handles AttachmentRequiredFile.ServerValidate
            If DontValidate = 1 Then
                GoTo Skipp
            End If
            'If PerformValidation = 1 Then
            If AttachmentsSelecter.FileName = "" Or AttachmentsSelecter.HasFile = False Or AttachmentsSelecter.PostedFiles.Count = 0 Then
                args.IsValid = False
            End If
    skipp:
            'End If
        End Sub
        Protected Sub AttachmentFilesCount_ServerValidate(source As Object, args As ServerValidateEventArgs) Handles AttachmentFilesCount.ServerValidate
    
            If PerformValidation = 1 Then
                If AttachmentsSelecter.HasFile = True Then
                    If AttachmentsSelecter.PostedFiles.Count > 5 Then
                        args.IsValid = False
                    End If
                End If
            End If
        End Sub
    
    
        Protected Sub CloseThisPage_Click(sender As Object, e As ImageClickEventArgs) Handles CloseThisPage.Click
            Response.Redirect("~\FollowingUpContentPages\MainMenu.aspx")
        End Sub
    
        Public Sub RemoveSourceNameSelectedIndxFromTargetName()
    
            Dim queryString As String
            Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
            Using connection As New SqlConnection(conString)
    
                connection.Open()
    
                queryString = "DELETE FROM NewToTargetsExg WHERE (LoadedByUserName=@UN)"
                Dim RemoveOldRecords As New SqlCommand(queryString, connection)
                RemoveOldRecords.Parameters.Add("@UN", SqlDbType.NVarChar)
                RemoveOldRecords.Parameters("@UN").Value = UserName
                RemoveOldRecords.ExecuteNonQuery()
    
                queryString = "INSERT INTO NewToTargetsExg(Indx,Name,LoadedByUserName) " &
                              "SELECT DISTINCT Indx,Name,@UN FROM AdministrationUnits WHERE (CAST(GETDATE() AS DateTime) BETWEEN FromDate And ToDate) "
                Dim LoadOriginalRecords As New SqlCommand(queryString, connection)
                LoadOriginalRecords.Parameters.Add("@UN", SqlDbType.NVarChar)
                LoadOriginalRecords.Parameters("@UN").Value = UserName
                LoadOriginalRecords.ExecuteNonQuery()
    
                queryString = "INSERT INTO NewToTargetsExg(Indx, Name,LoadedByUserName) " & _
                              "SELECT DISTINCT NewToTargets.Indx,NewToTargets.Name,NewToTargets.LoadedByUserName " & _
                              "FROM NewToTargets INNER JOIN ExternalEntities " & _
                              "ON ExternalEntities.Indx = NewToTargets.Indx " & _
                              "WHERE (NewToTargets.LoadedByUserName=@UN)"
                Dim AddRemainAdminUnits As New SqlCommand(queryString, connection)
                AddRemainAdminUnits.Parameters.Add("@UN", SqlDbType.NVarChar)
                AddRemainAdminUnits.Parameters("@UN").Value = UserName
                AddRemainAdminUnits.ExecuteNonQuery()
    
                queryString = "DELETE FROM NewToTargetsExg WHERE (Indx=@Ix) AND (LoadedByUserName=@UN)"
                Dim RemoveSelectedOfficeIndx As New SqlCommand(queryString, connection)
                RemoveSelectedOfficeIndx.Parameters.Add("@Ix", SqlDbType.Int)
                RemoveSelectedOfficeIndx.Parameters("@Ix").Value = SourceName.SelectedValue
                RemoveSelectedOfficeIndx.Parameters.Add("@UN", SqlDbType.NVarChar)
                RemoveSelectedOfficeIndx.Parameters("@UN").Value = UserName
                RemoveSelectedOfficeIndx.ExecuteNonQuery()
    
                queryString = "DELETE FROM NewToTargets WHERE (LoadedByUserName=@UN)"
                Dim RemoveOldRecordsExg As New SqlCommand(queryString, connection)
                RemoveOldRecordsExg.Parameters.Add("@UN", SqlDbType.NVarChar)
                RemoveOldRecordsExg.Parameters("@UN").Value = UserName
                RemoveOldRecordsExg.ExecuteNonQuery()
    
                queryString = "INSERT INTO NewToTargets(Indx,Name,LoadedByUserName) " & _
                              "SELECT * FROM NewToTargetsExg WHERE (LoadedByUserName=@UN)"
                Dim LoadRecordsBack As New SqlCommand(queryString, connection)
                LoadRecordsBack.Parameters.Add("@UN", SqlDbType.NVarChar)
                LoadRecordsBack.Parameters("@UN").Value = UserName
                LoadRecordsBack.ExecuteNonQuery()
    
                SDS1.DataBind()
                TargetName.DataBind()
    
            End Using
    
        End Sub
    
        Protected Sub NowToPostDateValidator_ServerValidate(source As Object, args As ServerValidateEventArgs) Handles NowToPostDateValidator.ServerValidate
    
            If OtherDate.Checked = True Then
    
                PostDate = Date.Parse(PostDateTxtBox.Text)
                If DateDiff(DateInterval.Minute, PostDate, Now()) < 0 Then
                    args.IsValid = False
                End If
            ElseIf NowDate.Checked = True Then
                PostDate = Now()
            End If
    
    
        End Sub
    
    
        Protected Sub PrivacyMessageValidator_ServerValidate(source As Object, args As ServerValidateEventArgs) Handles PrivacyMessageValidator.ServerValidate
    
            SourceIndx = SourceName.SelectedValue
            TargetIndx = TargetName.SelectedValue
            If IsTopSecret.Checked = True Then
    
                Dim SendingPrivacyError As Integer
                Dim ReceivingPrivacyError As Integer
    
                If TDClass.CheckIfExternal(SourceIndx) = 0 Then
                    SendingPrivacyError = SendingPrivacyMessageErrorChecking()
                    If SendingPrivacyError = 1 Then
                        PrivacyMessageValidator.ErrorMessage = "الأشخاص المخولين بالاطلاع على الرسالة ليس بينهم أحد من الطرف المرسل"
                        args.IsValid = False
                        GoTo SkipperLabel
                    End If
                End If
    
                If TDClass.CheckIfExternal(TargetIndx) = 0 Then
                    ReceivingPrivacyError = ReceivingPrivacyMessageErrorChecking()
                    If ReceivingPrivacyError = 1 Then
                        PrivacyMessageValidator.ErrorMessage = "الأشخاص المخولين بالاطلاع على الرسالة ليس بينهم أحد من الطرف المستقبل"
                        args.IsValid = False
                    End If
                End If
    
            End If
    
    SkipperLabel:
    
        End Sub
        Public Function SendingPrivacyMessageErrorChecking() As Integer
    
    
            SendingPrivacyMessageErrorChecking = 0
    
            If IsTopSecret.Checked = True Then
    
                Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
                Using connection As New SqlConnection(conString)
                    connection.Open()
    
                    Dim queryString As String
                    Dim AuthUserIndx As Integer
                    Dim PrivateAuthorizedUsersReader As SqlDataReader
                    queryString = "SELECT Indx FROM PrivateAuthorizedUsers WHERE (LoadedByUserName=@UN)"
                    Dim PrivateAuthorizedUsersReaderCollecter As New SqlCommand(queryString, connection)
                    PrivateAuthorizedUsersReaderCollecter.Parameters.Add("@UN", SqlDbType.NVarChar)
                    PrivateAuthorizedUsersReaderCollecter.Parameters("@UN").Value = UserName
                    PrivateAuthorizedUsersReader = PrivateAuthorizedUsersReaderCollecter.ExecuteReader
                    If PrivateAuthorizedUsersReader.HasRows Then
                        Do While PrivateAuthorizedUsersReader.Read()
                            AuthUserIndx = PrivateAuthorizedUsersReader(0)
                            If AuthUserIndx <> 0 Then
                                If TDClass.IsAuthorizedIx(SourceIndx, AuthUserIndx) = 1 Then
                                    GoTo SendSkipingPoint
                                End If
                            End If
                        Loop
                        PrivateAuthorizedUsersReader.Close()
                    End If
                    SendingPrivacyMessageErrorChecking = 1
    
                End Using
            End If
    
    SendSkipingPoint:
        End Function
    
        Public Function ReceivingPrivacyMessageErrorChecking() As Integer
    
    
            ReceivingPrivacyMessageErrorChecking = 0
    
            If IsTopSecret.Checked = True Then
    
                Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
                Using connection As New SqlConnection(conString)
                    connection.Open()
    
                    Dim queryString As String
                    Dim AuthUserIndx As Integer
                    Dim PrivateAuthorizedUsersReader As SqlDataReader
                    queryString = "SELECT Indx FROM PrivateAuthorizedUsers WHERE (LoadedByUserName=@UN)"
                    Dim PrivateAuthorizedUsersReaderCollecter As New SqlCommand(queryString, connection)
                    PrivateAuthorizedUsersReaderCollecter.Parameters.Add("@UN", SqlDbType.NVarChar)
                    PrivateAuthorizedUsersReaderCollecter.Parameters("@UN").Value = UserName
                    PrivateAuthorizedUsersReader = PrivateAuthorizedUsersReaderCollecter.ExecuteReader
                    If PrivateAuthorizedUsersReader.HasRows Then
                        Do While PrivateAuthorizedUsersReader.Read()
                            AuthUserIndx = PrivateAuthorizedUsersReader(0)
                            If AuthUserIndx <> 0 Then
                                If TDClass.IsAuthorizedIx(TargetIndx, AuthUserIndx) = 1 Then
                                    GoTo ReceivingSkipingPoint
                                End If
                            End If
                        Loop
                        PrivateAuthorizedUsersReader.Close()
                    End If
                    ReceivingPrivacyMessageErrorChecking = 1
    
                End Using
            End If
    
    ReceivingSkipingPoint:
        End Function
    
        Protected Sub SourceName_SelectedIndexChanged(sender As Object, e As EventArgs) Handles SourceName.SelectedIndexChanged
            SourceIndx = SourceName.SelectedValue
        End Sub
    
        Protected Sub TargetName_SelectedIndexChanged(sender As Object, e As EventArgs) Handles TargetName.SelectedIndexChanged
            TargetIndx = TargetName.SelectedValue
        End Sub
    
        Public Sub UploadAttachments(ByVal StorageUnit As Integer)
            Dim CharString = "ABCDEF"
            Dim i As Integer = 0
            Dim ServerPathPF As String = TDClass.GetTheServerStoragePath(StorageUnit)
            For Each postedFile As HttpPostedFile In AttachmentsSelecter.PostedFiles
                Dim fileName As String = Path.GetFileName(postedFile.FileName)
    
                Dim TheSelectedFileSourcePath As String = postedFile.FileName
                Dim DotPos As Integer = InStr(TheSelectedFileSourcePath, ".")
                Dim FileExtension As String = TheSelectedFileSourcePath.Substring(DotPos, Len(TheSelectedFileSourcePath) - DotPos)
                TheAttachedFileServerPath = ServerPathPF & LetterIDPublic & CharString(i) & "." & FileExtension
                If System.IO.File.Exists(TheAttachedFileServerPath) = True Then
                    System.IO.File.Delete(TheAttachedFileServerPath)
                End If
                postedFile.SaveAs(TheAttachedFileServerPath)
                i = i + 1
            Next
        End Sub
    
        Public Sub UploadCopyAttachments(ByVal StorageUnit As Integer, ByVal LetterID As String)
    
            Dim CharString = "ABCDEF"
            Dim i As Integer = 0
            Dim ServerPathPF As String = TDClass.GetTheServerStoragePath(StorageUnit)
            For Each postedFile As HttpPostedFile In AttachmentsSelecter.PostedFiles
                Dim fileName As String = Path.GetFileName(postedFile.FileName)
    
                Dim TheSelectedFileSourcePath As String = postedFile.FileName
                Dim DotPos As Integer = InStr(TheSelectedFileSourcePath, ".")
                Dim FileExtension As String = TheSelectedFileSourcePath.Substring(DotPos, Len(TheSelectedFileSourcePath) - DotPos)
                TheAttachedFileServerPath = ServerPathPF & LetterID & CharString(i) & "." & FileExtension
                If System.IO.File.Exists(TheAttachedFileServerPath) = True Then
                    System.IO.File.Delete(TheAttachedFileServerPath)
                End If
                postedFile.SaveAs(TheAttachedFileServerPath)
                i = i + 1
            Next
    
    
        End Sub
    
        'Protected Sub EditFollowUpID_Click(sender As Object, e As EventArgs) Handles EditFollowUpID.Click
    
        '    Dim queryString As String
        '    Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
        '    Using connection As New SqlConnection(conString)
        '        connection.Open()
    
        '        queryString = "SELECT COUNT(*) FROM NewPosting WHERE (FollowUpID=@LID)"
        '        Dim CheckIfSaved1 As New SqlCommand(queryString, connection)
        '        CheckIfSaved1.Parameters.Add("@LID", SqlDbType.NVarChar)
        '        CheckIfSaved1.Parameters("@LID").Value = FollowUpID.Text
        '        Dim IsSaved1 As Integer = CheckIfSaved1.ExecuteScalar
    
        '        queryString = "SELECT COUNT(*) FROM Postings WHERE (FollowUpID=@LID)"
        '        Dim CheckIfSaved2 As New SqlCommand(queryString, connection)
        '        CheckIfSaved2.Parameters.Add("@LID", SqlDbType.NVarChar)
        '        CheckIfSaved2.Parameters("@LID").Value = FollowUpID.Text
        '        Dim IsSaved2 As Integer = CheckIfSaved2.ExecuteScalar
    
        '        StoreDraftChangeLetterIDIntoSession()
        '        If IsSaved1 + IsSaved2 > 0 Then
        '            Response.Redirect("~\NewPosting\ChangeFollowUpID.aspx")
        '        Else
        '            Response.Redirect("~\NewPosting\NoLetterIDChanged.aspx")
        '        End If
    
        '    End Using
    
        'End Sub
    
        Public Sub StoreDraftChangeFollowUpIDIntoSession()
    
    
            Session("DraftChangeLetterIDSource") = SourceName.SelectedValue
            Session("DraftChangeLetterIDTarget") = TargetName.SelectedValue
    
            Session("DraftChangeLetterIDValue") = LetterIDTxtBox.Text
            Session("DraftChangeFollowUpIDValue") = FollowUpID.Text
    
            If AloneCB.Checked = True Then
                Session("DraftChangeLetterIDAloneCB") = "true"
            ElseIf AloneCB.Checked = False Then
                Session("DraftChangeLetterIDAloneCB") = "false"
            End If
    
            If MultiCB.Checked = True Then
                Session("DraftChangeLetterIDMultiCB") = "true"
            ElseIf MultiCB.Checked = False Then
                Session("DraftChangeLetterIDMultiCB") = "false"
            End If
    
            If NowDate.Checked = True Then
                Session("DraftChangeLetterIDNowDate") = "true"
            Else
                Session("DraftChangeLetterIDNowDate") = "false"
            End If
    
            If IsTopSecret.Checked = True Then
                Session("DraftChangeLetterIDIsTopSecret") = "true"
            Else
                Session("DraftChangeLetterIDIsTopSecret") = "false"
            End If
    
            Session("DraftChangeLetterIDDateVal") = PostDateTxtBox.Text
    
            Session("DraftChangeLetterIDSubject") = SubjectTxtBox.Text
            Session("DraftChangeLetterIDComments") = CommentsTxtBox.Text
            Session("DraftChangeLetterIDTypeDDLValue") = PostTypeDDL.SelectedValue
            If PostTypeDDL.SelectedValue = "طلب" Then
                Session("DraftChangeLetterIDRAP") = CInt(RAPTxtBox.Text)
            End If
            Session("DraftChangeLetterIDImportanceValue") = ImportanceDD.SelectedValue
    
        End Sub
    
        Protected Sub OKbtn_Click(sender As Object, e As EventArgs) Handles OKbtn.Click
    
            Dim Panel1Validator As CustomValidator = CType(Panel1.FindControl("IncomingDateValidator"), CustomValidator)
            Dim Panel1IncomingDateValue As TextBox = CType(Panel1.FindControl("Panel1IncomingDateValue"), TextBox)
            Dim Panel1PostRefNo As TextBox = CType(Panel1.FindControl("Panel1PostRefNo"), TextBox)
    
            If IsDate(Panel1IncomingDateValue.Text) = True Then
                If DateDiff("d", Now(), Panel1IncomingDateValue.Text) > 0 Then
                    Panel1Validator.IsValid = False
                    ModalPopupExtender1.Show()
                    GoTo Skipper
                End If
            End If
    
            Dim queryString As String
            Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
            Using connection As New SqlConnection(conString)
                connection.Open()
    
                queryString = "DELETE FROM IncomingLetterInfo WHERE (LoadedByUserIndx=@Ix)"
                Dim RemoveOldIncomingLetterInfo As New SqlCommand(queryString, connection)
                RemoveOldIncomingLetterInfo.Parameters.Add("@Ix", SqlDbType.Int)
                RemoveOldIncomingLetterInfo.Parameters("@Ix").Value = TDClass.GetLoggingUserIndxValue(UserName)
                RemoveOldIncomingLetterInfo.ExecuteNonQuery()
    
                If Panel1IncomingDateValue.Text = "" And Panel1PostRefNo.Text = "" Then
                    GoTo Skipper
                End If
    
                If Panel1IncomingDateValue.Text <> "" And Panel1PostRefNo.Text <> "" Then
                    queryString = "INSERT INTO IncomingLetterInfo(IncomePostDate,IncomeRefNo,LoadedByUserIndx) VALUES(@PD,@Ref,@UI)"
                    Dim StoreIncomingInfo As New SqlCommand(queryString, connection)
                    StoreIncomingInfo.Parameters.Add("@PD", SqlDbType.Date)
                    StoreIncomingInfo.Parameters("@PD").Value = Date.Parse(Panel1IncomingDateValue.Text)
                    StoreIncomingInfo.Parameters.Add("@Ref", SqlDbType.NVarChar)
                    StoreIncomingInfo.Parameters("@Ref").Value = Panel1PostRefNo.Text
                    StoreIncomingInfo.Parameters.Add("@UI", SqlDbType.Int)
                    StoreIncomingInfo.Parameters("@UI").Value = TDClass.GetLoggingUserIndxValue(UserName)
                    StoreIncomingInfo.ExecuteNonQuery()
                ElseIf Panel1IncomingDateValue.Text = "" And Panel1PostRefNo.Text <> "" Then
                    queryString = "INSERT INTO IncomingLetterInfo(IncomeRefNo,LoadedByUserIndx) VALUES(@Ref,@UI)"
                    Dim StoreIncomingInfo As New SqlCommand(queryString, connection)
                    StoreIncomingInfo.Parameters.Add("@Ref", SqlDbType.NVarChar)
                    StoreIncomingInfo.Parameters("@Ref").Value = Panel1PostRefNo.Text
                    StoreIncomingInfo.Parameters.Add("@UI", SqlDbType.Int)
                    StoreIncomingInfo.Parameters("@UI").Value = TDClass.GetLoggingUserIndxValue(UserName)
                    StoreIncomingInfo.ExecuteNonQuery()
                ElseIf Panel1IncomingDateValue.Text <> "" And Panel1PostRefNo.Text = "" Then
                    queryString = "INSERT INTO IncomingLetterInfo(IncomePostDate,LoadedByUserIndx) VALUES(@PD,@UI)"
                    Dim StoreIncomingInfo As New SqlCommand(queryString, connection)
                    StoreIncomingInfo.Parameters.Add("@PD", SqlDbType.Date)
                    StoreIncomingInfo.Parameters("@PD").Value = Date.Parse(Panel1IncomingDateValue.Text)
                    StoreIncomingInfo.Parameters.Add("@UI", SqlDbType.Int)
                    StoreIncomingInfo.Parameters("@UI").Value = TDClass.GetLoggingUserIndxValue(UserName)
                    StoreIncomingInfo.ExecuteNonQuery()
                End If
    
            End Using
    
    Skipper:
        End Sub
    
    
        Public Sub LoadIncomingPostInfo()
    
            Dim Panel1Validator As CustomValidator = CType(Panel1.FindControl("IncomingDateValidator"), CustomValidator)
            Dim Panel1IncomingDateValue As TextBox = CType(Panel1.FindControl("Panel1IncomingDateValue"), TextBox)
            Dim Panel1PostRefNo As TextBox = CType(Panel1.FindControl("Panel1PostRefNo"), TextBox)
    
    
            Dim conString = ConfigurationManager.ConnectionStrings("TrackingConnectionString").ConnectionString
            Using connection As New SqlConnection(conString)
                connection.Open()
    
                queryString = "SELECT IncomePostDate,IncomeRefNo FROM IncomingLetterInfo WHERE (LoadedByUserIndx=@Ix)"
                Dim GetIncomingInfo As New SqlCommand(queryString, connection)
                GetIncomingInfo.Parameters.Add("@Ix", SqlDbType.Int)
                GetIncomingInfo.Parameters("@Ix").Value = TDClass.GetLoggingUserIndxValue(Session("username"))
                Dim IncomingInfo As SqlDataReader = GetIncomingInfo.ExecuteReader
    
                If IncomingInfo.HasRows Then
                    IncomingInfo.Read()
                    If IsDBNull(IncomingInfo(0)) = False Then
                        Dim IncomingDate As Date = IncomingInfo(0)
                        Panel1IncomingDateValue.Text = Format(IncomingDate, "dd-MMMM-yyyy")
                    End If
    
                    If IsDBNull(IncomingInfo(1)) = False Then
                        Panel1PostRefNo.Text = IncomingInfo(1)
                    End If
    
                    IncomingInfo.Close()
                End If
    
            End Using
    
        End Sub
    
    End Class

    Tuesday, October 2, 2018 5:31 PM

All replies

  • User475983607 posted

    Keep FileUpload control with its attached files after any buttons postbacks

    It is not possible with a full post back because the page is refreshed with new content.

    I have a FileUpload control "AttachmentsSelecter" . The problem I have is that whenever I clicked any button that make postback, it loses the attached file. I used the <UpdatePanel> and <ContentTemplate>, and <PostBackTrigger> but it still loses the attachment.

    Basically, the file upload element cannot be refreshed.  Otherwise, the user must re-select the file.  The browser does not allow a web server to select files on the user's machine.

    Tuesday, October 2, 2018 5:46 PM
  • User-786564416 posted

    So do you mean that the user should perform everything and the last thing he should do is the files attachments?

    Tuesday, October 2, 2018 8:37 PM
  • User-893317190 posted

    Hi alihusain_77,

    You should put buttons you don't want to cause the uploadfile to upload in updaepanels  and put the uploadfile outside updatepanle.

    Below is my test sample.

       <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
       
                   
          
            <asp:UpdatePanel ID="UpdatePanel2" runat="server">
    
                <ContentTemplate>
                        <asp:Button ID="Button2" runat="server" Text="button in update panel" /><br /><br />
                </ContentTemplate>
            </asp:UpdatePanel>
        
    
             <asp:FileUpload ID="FileUpload1" runat="server" AllowMultiple="true" /><br />
                    <asp:Label ID="Label1" runat="server" Text=""></asp:Label><br />
            <asp:Button ID="Button1" runat="server" Text="button outside the update panel" OnClick="Button1_Click"  />

    Code behind.

      protected void Button1_Click(object sender, EventArgs e)
            {
                Label1.Text ="you have upload "+ FileUpload1.PostedFiles.Count +"files";
            
            }

    The result.

    Best regards,

    Ackerly Xu

    Wednesday, October 3, 2018 2:14 AM