using System;
using System.Data;
using System.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Resources;
using System.Globalization;
using System.Threading;
using System.Net.Mail;
using DevExpress.Web;
using System.IO;
using System.Collections;
/****************************************************************************************************************************
* Project Name    : TimeCheck                         Started Date  : 08-Oct-2016
* Module          : Leave Sanction                    Last Modified : 09-Oct-2016
* Programmer      : Karthikeyan.R
* Current Storage : 
* BackUp          :
****************************************************************************************************************************/
public partial class Transactions_TA_UI_Transaction_Sanctions : Base.BasePage
{
    #region Variable Declaration
    string previousCat = "";
    int firstRow = -1;
    ResourceManager rm;
    CultureInfo ci;
    Cls_CheckUser objCheckUser = new Cls_CheckUser();
    DataSet ds_Checkuser = new DataSet();
    LeaveApplicationEventData objLeaveApplicationEventData = new LeaveApplicationEventData();
    ManualEntryEventData objManualEntryEventData = new ManualEntryEventData();
    TimeSheetEntry objtimeSheet = new TimeSheetEntry();
    LeaveEventData objLeave = new LeaveEventData();
    cls_Common objClassCommon = new cls_Common();
    SMSNotification objsms = new SMSNotification();
    DataTable dtPermissionSanctionView = new DataTable();
    EmployeeEventData objEmployee = new EmployeeEventData();
    CCGroupEventData_Angler objCCGroup = new CCGroupEventData_Angler();
    PermissionEventData objPermissionEventData = new PermissionEventData();
    DateTime CurrentDate;
    int intCompanyId;
    DataTable dtLeaveTransactionView, dtSanctionView, dtLeaveTransactionViewBulk, dtManualEntrySanctionView, dtMyprofileSanctionView = new DataTable();
    DataSet dsEmployeeGroup, ds_ReportingToSanctionAuthorityList, ds_EmailIdOfSanctionAuthority, dsEmailIdOfReportingTo, dsRecordsCount = new DataSet();
    Int64 gintManualTimeEntryId, gintUserId;
    string[] chkBoxIDs;
    string TimeFormatMail = string.Empty;
    string gstrDateFormat, strFromDateTime, strToDateTime, levelName, startDate, strOnDutyApplicationDate, Fromdatettime, Todatettime, strEmpFirstName, strEmpLastName, strEmployeeEmailId, strEmailIdSanctioningAuthority;
    string endDate, LevelId, Status, From_Date, To_Date, StartMonth, EndMonth, StartYear, EndYear, strlevelName, gstrTimeFormat, NewStatus, Employee_Code_Id;
    string LastName, lblPermissionDate, lblPermissionFromTime, lblPermissionToTime, strSwipeCardNo, strEmployeeName, strEmployeeCodeId, source_Language = string.Empty;
    string Remarks, strEmailIdSanctionAuthority = "", EmpCategory, EmpType, strEmailIdReportingTo = "", EmployeeName, empEmailId, strLeaveApplicationDate, strNoOfDays, Leave_FromDate, Leave_ToDate, strReason;
    string NotSendedEmployeeCodeId = "";
    int month, year, date, TotalDays, intCount, Permission_Id, vmonthValue, InsertCount, LeaveApplication_Id, Employee_Id, LeaveTypeId = 0;
    double NumberOfDays;
    bool checkRecordExists, Isprocessedrecord;
    bool CheckGrid, statusProcess = false;
    bool blnCheckEmail, blnCheckSMS = true;
    bool checkEmail = true;
    bool isClear = false;
    #endregion
    #region PageLoad Events
    protected override void Page_Load(object sender, EventArgs e)
    {
        base.Page_Load(sender, e);
        if (!Page.IsPostBack)
        {
            base.CheckPages(0);
            //Todo:need to add this line into new file.
            objClassCommon.menu("Approvals", "248");
            Hidden1.Value = Convert.ToString(Session["IDateFormat"]);
            // btnTemplate.Text = "&nbsp&nbsp MC File";
        }
        string source_Language;
        source_Language = Convert.ToString(Session["Session_ActiveLanguage"]);
        rm = new ResourceManager(source_Language, System.Reflection.Assembly.Load("App_GlobalResources"));
        ci = Thread.CurrentThread.CurrentCulture;
        site.SiteMapProvider = Convert.ToString(Session["SiteMapProvider"]);
        gdLeaveSanctionView.Styles.CssFilePath = Convert.ToString(Session["GridCSS"]);
        gdLeaveSanctionViewBulk.Styles.CssFilePath = Convert.ToString(Session["GridCSS"]);
        gdPermissionSanctionView.Styles.CssFilePath = Convert.ToString(Session["GridCSS"]);
        gdPermissionSanctionViewBulk.Styles.CssFilePath = Convert.ToString(Session["GridCSS"]);
        gdOndutySanctionView.Styles.CssFilePath = Convert.ToString(Session["GridCSS"]);
        gdOndutySanctionViewBulk.Styles.CssFilePath = Convert.ToString(Session["GridCSS"]);
        gdMyProfileSanctionView.Styles.CssFilePath = Convert.ToString(Session["GridCSS"]);
        gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
        if (!IsPostBack)
        {
            LoadStrings(ci);
            UserRights();
            txtFromDate.Text = (Convert.ToDateTime(CurrentMonthStartDate().ToString())).ToString(Session["MDateFormat"].ToString());
            txtToDate.Text = (Convert.ToDateTime(NextMonthEndDate())).ToString(Session["MDateFormat"].ToString());
            BindingEmployeeCategoryandType();
            string strSetAlert = "";
            strSetAlert = strSetAlert + "<script language='javascript'>";
            strSetAlert = strSetAlert + "MaxLengthh('" + rm.GetString("Alert_MaximumLengthis", ci) + "');";
            strSetAlert = strSetAlert + "SetAlertMessages('" + rm.GetString("Alert_EnterDate", ci) + "','" + rm.GetString("Alert_EnterToDate", ci) + "','" + rm.GetString("Alert_SelectStatus", ci) + "');";
            strSetAlert = strSetAlert + "SetAlertCheckDate('" + rm.GetString("Alert_Validmonthdatefourdigit", ci) + "','" + rm.GetString("Alert_Validdatemonthfourdigit", ci) + "','" + rm.GetString("Alert_Invalidyearentry", ci) + "','" + rm.GetString("Alert_Invalidmonthentry", ci) + "','" + rm.GetString("Alert_Invaliddateentry", ci) + "','" + rm.GetString("Alert_IncorrectdateformatDDMONYYYY", ci) + "','" + rm.GetString("Alert_Entertime", ci) + "','" + rm.GetString("Alert_Invalidvalueforhours", ci) + "','" + rm.GetString("Alert_Invalidvalueforminites", ci) + "','" + rm.GetString("Alert_Invalidtimeformat1", ci) + "','" + rm.GetString("Alert_PleaseentervalidDateandTime", ci) + "','" + rm.GetString("Alert_ValiddatemonthMMDDYYHHMM", ci) + "','" + rm.GetString("Alert_ValiddatemonthMMDDYYHHMMTT", ci) + "','" + rm.GetString("Alert_PleaseentervalidDateandTime", ci) + "','" + rm.GetString("Alert_Invalidvalueforhours", ci) + "','" + rm.GetString("Alert_Invalidvalueforminites", ci) + "');";
            strSetAlert = strSetAlert + "SetAlertMessages_DeleteRestore('" + rm.GetString("Alert_ConfirmDelete") + "','" + rm.GetString("Alert_SelectItemsToDelete") + "','" + rm.GetString("Alert_ConfirmDeletePermanent") + "','" + rm.GetString("Alert_Areyousuretorestore") + "','" + rm.GetString("Alert_SelectItemsToRestore") + "','" + rm.GetString("Alert_SelectItemToForwarded") + "','" + rm.GetString("Alert_SelectItemToApproved") + "');";
            strSetAlert = strSetAlert + "</script>";
            Page.RegisterStartupScript("SetAlertMessages", strSetAlert);
        }
        if (Session["SanctionType"] != null)
        {
            switch (Convert.ToString(Session["SanctionType"]))
            {
                case "Leave":
                    #region LeaveSanction
                    bindLeaveSanctionDetails("Load");
                    LoadDiv("LeaveSanction");
                    #endregion
                    break;
                case "LeaveBulk":
                    #region LeaveSanctionBulk
                    bindLeaveSanctionDetailsForBulkApproval("Load");
                    LoadDiv("LeaveSanctionBulk");
                    #endregion
                    break;
                case "Permission":
                    #region PermissionSanction
                    BindPermissionSanction("Load");
                    LoadDiv("PermissionSanction");
                    #endregion
                    break;
                case "PermissionBulk":
                    #region PermissionSanctionBulk
                    BindPermissionSanction("Load");
                    LoadDiv("PermissionSanctionBulk");
                    #endregion
                    break;
                case "Onduty":
                    #region OndutySanction
                    BindOndutySanctionDetails("Load");
                    LoadDiv("OndutySanction");
                    #endregion
                    break;
                case "OndutyBulk":
                    #region OndutySanctionBulk
                    BindOndutySanctionDetails("Load");
                    LoadDiv("OndutySanctionBulk");
                    #endregion
                    break;
                case "MyProfile":
                    #region MyProfile
                    bindMyProfileDetails("Load");
                    LoadDiv("MyProfile");
                    #endregion
                    break;
            }
        }
        if (!IsPostBack)
        {
            if (Session["SanctionSelected"] != null && Convert.ToString(Session["SanctionSelected"]) != "")
            {
                switch (Convert.ToString(Session["SanctionSelected"]))
                {
                    case "1":
                        rbLeaveApplication.Checked = true;
                        GetFilter();
                        Session["SanctionSelected"] = "";
                        break;
                    case "2":
                        rbPermission.Checked = true;
                        GetFilter();
                        Session["SanctionSelected"] = "";
                        break;
                    case "3":
                        rbOnduty.Checked = true;
                        GetFilter();
                        Session["SanctionSelected"] = "";
                        break;
                    case "4":
                        rbtnTimesheet.Checked = true;
                        GetFilter();
                        Session["SanctionSelected"] = "";
                        break;
                    case "5":
                        rbtnMyProfile.Checked = true;
                        GetFilter();
                        Session["SanctionSelected"] = "";
                        break;
                    default:
                        break;
                }
                if (Request.QueryString["Type"] == null)
                    LoadDiv("clear");
            }
            else
            {
                LoadDiv("clear");
            }
        }
    }
    private void UserSelected_SanctionType()
    {
        if (Session["SanctionType"] != null)
        {
            switch (Convert.ToString(Session["SanctionType"]))
            {
                case "Leave":
                    bindLeaveSanctionDetails("Load");
                    LoadDiv("LeaveSanction");
                    break;
                case "LeaveBulk":
                    bindLeaveSanctionDetailsForBulkApproval("Load");
                    LoadDiv("LeaveSanctionBulk");
                    break;
                case "Permission":
                    BindPermissionSanction("Load");
                    LoadDiv("PermissionSanction");
                    break;
                case "PermissionBulk":
                    BindPermissionSanction("Load");
                    LoadDiv("PermissionSanctionBulk");
                    break;
                case "Onduty":
                    BindOndutySanctionDetails("Load");
                    LoadDiv("OndutySanction");
                    break;
                case "OndutyBulk":
                    BindOndutySanctionDetails("Load");
                    LoadDiv("OndutySanctionBulk");
                    break;
            }
        }
    }
    #endregion
    #region User Defined Functions
    #region LeaveSanction & Bulk
    public void bindLeaveSanctionDetails(string isLoad)
    {
        if (Convert.ToString(Session["UserGroupName"]) == "SuperAdmin" || Convert.ToString(Session["HasSpecialRights"]) == "True")
            dtLeaveTransactionView = objLeaveApplicationEventData.GetLeaveSanctionDetailsForSuperAdmin(Convert.ToInt32(Session["EmpAutoID"]), Convert.ToString(Session["LevelId"]), Convert.ToString(Session["Status"]), Convert.ToString(Session["SanFromDate"]), Convert.ToString(Session["SanToDate"]), Convert.ToString(Session["SanSwipeCardNo"]), Convert.ToString(Session["SanEmployeeName"]), Convert.ToString(Session["SanEmployeeCodeId"]), Convert.ToString(Session["UserGroupName"]), Convert.ToInt16(Session["parentLevelId"]), Convert.ToInt16(Session["SanEmpCategory"]), Convert.ToInt16(Session["SanEmpType"]));
        else
            dtLeaveTransactionView = objLeaveApplicationEventData.GetLeaveSanctionDetails(Convert.ToInt32(Session["EmpAutoId"]), Convert.ToString(Session["LevelId"]), Convert.ToString(Session["Status"]), Convert.ToDateTime(Session["SanFromDate"]), Convert.ToDateTime(Session["SanToDate"]), Convert.ToString(Session["SanSwipeCardNo"]), Convert.ToString(Session["SanEmployeeName"]), Convert.ToString(Session["SanEmployeeCodeId"]), Convert.ToString(Session["UserGroupName"]), Convert.ToInt16(Session["parentLevelId"]), Convert.ToInt16(Session["SanEmpCategory"]), Convert.ToInt16(Session["SanEmpType"]));
        if (dtLeaveTransactionView.Rows.Count > 0)
        {
            gdLeaveSanctionView.DataSource = dtLeaveTransactionView;
            gdLeaveSanctionView.DataBind();
            LoadDiv("LeaveSanction");
        }
        else
        {
            if (isLoad == "Unload")
                Message(rm.GetString("Alert_Thereisnorecord", ci));
            LoadDiv("clear");
            return;
        }
    }
    public void bindLeaveSanctionDetailsForBulkApproval(string isLoad)
    {
        if (Convert.ToString(Session["UserGroupName"]) == "SuperAdmin" || Convert.ToString(Session["HasSpecialRights"]) == "True")
            dtLeaveTransactionViewBulk = objLeaveApplicationEventData.GetLeaveSanctionDetailsForSuperAdmin(Convert.ToInt32(Session["EmpAutoID"]), Convert.ToString(Session["LevelId"]), Convert.ToString(Session["Status"]), Convert.ToString(Session["SanFromDate"]), Convert.ToString(Session["SanToDate"]), Convert.ToString(Session["SanSwipeCardNo"]), Convert.ToString(Session["SanEmployeeName"]), Convert.ToString(Session["SanEmployeeCodeId"]), Convert.ToString(Session["UserGroupName"]), Convert.ToInt16(Session["LevelId"]), Convert.ToInt16(Session["SanEmpCategory"]), Convert.ToInt16(Session["SanEmpType"]));
        else
            dtLeaveTransactionViewBulk = objLeaveApplicationEventData.GetLeaveSanctionDetails(Convert.ToInt32(Session["EmpAutoId"]), Convert.ToString(Session["LevelId"]), Convert.ToString(Session["Status"]), Convert.ToDateTime(Session["SanFromDate"]), Convert.ToDateTime(Session["SanToDate"]), Convert.ToString(Session["SanSwipeCardNo"]), Convert.ToString(Session["SanEmployeeName"]), Convert.ToString(Session["SanEmployeeCodeId"]), Convert.ToString(Session["UserGroupName"]), Convert.ToInt16(Session["LevelId"]), Convert.ToInt16(Session["SanEmpCategory"]), Convert.ToInt16(Session["SanEmpType"]));
        if (dtLeaveTransactionViewBulk.Rows.Count > 0)
        {
            gdLeaveSanctionViewBulk.DataSource = dtLeaveTransactionViewBulk;
            gdLeaveSanctionViewBulk.DataBind();
            LoadDiv("LeaveSanctionBulk");
        }
        else
        {
            if (isLoad == "Unload")
                Message(rm.GetString("Alert_Thereisnorecord", ci));
            LoadDiv("clear");
            return;
        }
    }
    private string[] commaStringToArray(string strComma)
    {
        string[] strArray;
        strArray = strComma.Split(new char[] { ',' });
        string[] intArray = new string[strArray.Length];
        for (int i = 0; i < strArray.Length; i++)
            intArray[i] = Convert.ToString(strArray[i]);
        return intArray;
    }
    private void SanctionViewDetails(int LeaveApplication_Id)
    {
        dtSanctionView = objLeaveApplicationEventData.GetLeaveApplicationByLeaveApplicationId(LeaveApplication_Id);
        if (dtSanctionView.Rows.Count > 0)
        {
            ViewState["Employee_code_Id"] = Convert.ToString(dtSanctionView.Rows[0]["Employee_code_Id"]);
            ViewState["StatusOnLoad"] = Convert.ToString(dtSanctionView.Rows[0]["Status"]);
            ViewState["StatusBorrow"] = Convert.ToString(dtSanctionView.Rows[0]["IsBorrow"]);
            ViewState["LeaveType"] = Convert.ToString(dtSanctionView.Rows[0]["LeaveType"]);
        }
    }
    private void SendMailToApplicant(int LevelID, int LeaveApplication_Id, string EmployeeEmailId, string strEmailIdReportingTo, string strEmailIdSanctionAuthority, string EmployeeName, string Status, string Remarks, string LeaveApplicationDate, string NoOfDays, string strLeaveType, string FromDate, string Todate, string FromSession, string ToSession, string Reason)
    {
        MailMessage mailMessage = new MailMessage();
        string scriptText;
        DataTable dtTableScript = new DataTable();
        try
        {
            dtTableScript = objLeaveApplicationEventData.GetEmailScripts("Leave Application Sanction By Reporting to Person");
            if (dtTableScript.Rows.Count > 0)
            {
                switch (strLeaveType)
                {
                    case "Restricted Holiday":
                        strLeaveType = rm.GetString("Holiday_RestrictedHoliday", ci);
                        break;
                    case "Comp Off":
                        strLeaveType = rm.GetString("Caption_CompOff", ci);
                        break;
                    case "LOP":
                        strLeaveType = strLeaveType.Replace("LOP", rm.GetString("lbl_LOP", ci));
                        break;
                    case "ESI":
                        strLeaveType = rm.GetString("Caption_ESI", ci);
                        break;
                    default:
                        if (strLeaveType.Contains("Leave"))
                            strLeaveType = strLeaveType.Replace("Leave", rm.GetString("LeaveApplication_Leave", ci));
                        break;
                }
                scriptText = Convert.ToString(dtTableScript.Rows[0]["ScriptText"]);
                string Employee_Code_Id = Convert.ToString(ViewState["Employee_code_Id"]);
                // As per elite partner requisition, mail should be trigger from admin id, whatever we configured in setting page.
                //25-Dec-2019 02:06 PM
                //if (Session["loginEmailId"] != null && Convert.ToString(Session["loginEmailId"]) != string.Empty)
                //{
                //    mailMessage.From = new MailAddress(Convert.ToString(Session["loginEmailId"]));
                //    strFromEmailId = Convert.ToString(Session["loginEmailId"]);
                //}
                //else
                //{
                mailMessage.From = new MailAddress(ConfigurationManager.AppSettings.Get("FromId"));
                //}
                if (Status == "Forwarded")
                {
                    if (strEmailIdSanctionAuthority != string.Empty)
                        mailMessage.To.Add(new MailAddress(strEmailIdSanctionAuthority));
                    if (empEmailId != string.Empty)
                        mailMessage.CC.Add(new MailAddress(empEmailId));
                }
                if (Session["loginEmailId"] != null && Convert.ToString(Session["loginEmailId"]) != string.Empty)
                {
                    if (strEmailIdSanctionAuthority != strEmailIdReportingTo)
                    {
                        if (Status != "Forwarded")
                        {
                            if (Convert.ToString(Session["loginEmailId"]) == strEmailIdSanctionAuthority)
                            {
                                if (empEmailId != string.Empty)
                                    mailMessage.To.Add(new MailAddress(empEmailId));
                                if (strEmailIdReportingTo != string.Empty)
                                    mailMessage.CC.Add(new MailAddress(strEmailIdReportingTo));
                            }
                            else if (Convert.ToString(Session["loginEmailId"]) == strEmailIdReportingTo)
                            {
                                if (empEmailId != string.Empty)
                                    mailMessage.To.Add(new MailAddress(empEmailId));
                            }
                        }
                    }
                    else
                    {
                        if (Status != "Forwarded")
                            if (empEmailId != string.Empty)
                                mailMessage.To.Add(new MailAddress(empEmailId));
                    }
                }
                else
                {
                    if (Status != "Forwarded")
                        if (empEmailId != string.Empty)
                            mailMessage.To.Add(new MailAddress(empEmailId));
                }
                mailMessage.Subject = rm.GetString("email_YourLeaveApplicationFor", ci) + " - " + FromDate + " | " + Employee_Code_Id + " - " + EmployeeName + " | " + Status;
                mailMessage.Body = scriptText.Replace("<<lblLeaveApplicationForm>>", rm.GetString("email_LeaveApplicationForm", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<lblEmployeeId>>", rm.GetString("email_EmployeeId", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<EmployeeId>>", Employee_Code_Id);
                mailMessage.Body = mailMessage.Body.Replace("<<lblEmployeeName>>", rm.GetString("email_EmployeeName", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<EmployeeName>>", EmployeeName);
                mailMessage.Body = mailMessage.Body.Replace("<<lblApplicationDate>>", rm.GetString("email_LeaveApplicationDate", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<ApplicationDate>>", LeaveApplicationDate);
                mailMessage.Body = mailMessage.Body.Replace("<<lblLeaveType>>", rm.GetString("lbl_leavetype", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<LeaveType>>", strLeaveType);
                mailMessage.Body = mailMessage.Body.Replace("<<lblLeaveDate>>", rm.GetString("email_LeaveDate", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<lblFromDate>>", rm.GetString("email_FromDate", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<FromDate>>", FromDate);
                mailMessage.Body = mailMessage.Body.Replace("<<lblToDate>>", rm.GetString("email_ToDate", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<ToDate>>", Todate);
                mailMessage.Body = mailMessage.Body.Replace("<<lblSession>>", rm.GetString("email_Session", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<FromSession>>", FromSession);
                mailMessage.Body = mailMessage.Body.Replace("<<lblFromSession>>", rm.GetString("email_FromDate", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<ToSession>>", ToSession);
                mailMessage.Body = mailMessage.Body.Replace("<<lblToSession>>", rm.GetString("email_ToDate", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<lblNumberDaysApplied>>", rm.GetString("email_NumberOfDaysApplied", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<NumberDaysApplied>>", NoOfDays);
                mailMessage.Body = mailMessage.Body.Replace("<<lblStatus>>", rm.GetString("email_Status", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<Status>>", Status);
                mailMessage.Body = mailMessage.Body.Replace("<<lblreason>>", rm.GetString("email_Reason", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<reason>>", Reason);
                mailMessage.Body = mailMessage.Body.Replace("<<lblRemarks>>", rm.GetString("email_Remarks", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<Remarks>>", Remarks);
                if (Status == "Forwarded")
                    mailMessage.Body = mailMessage.Body.Replace("<<LinkData>>", Convert.ToString(Session["HostServerURL"]) + "?LeaveApplication_Id=" + Convert.ToString(LeaveApplication_Id) + "&LevelId=" + LevelID + "&Status=" + Status + "&ApprovalType=Leave");
                else
                {
                    string strReplaceText = "<font face=\"Arial\" size=\"2\"><a href=\"<<LinkData>>\">Click here for approval</a></font>";
                    mailMessage.Body = mailMessage.Body.Replace(strReplaceText, string.Empty);
                }
                objClassCommon.SendMail(mailMessage);
            }
            else
            {
                checkEmail = false;
                //objLeaveApplicationEventData.InsertLeaveApplicationDetailsInEmailTrigger(LeaveApplication_Id, strFromEmailId, EmployeeEamilId, strEmailIdReportingTo, rm.GetString("email_YourLeaveApplicationFor", ci) + " - " + lblFromDate.Text + " - " + lblToDate.Text + " | " + Status, mailMessage.Body.ToString(), "", "LeaveSanction");
            }
        }
        catch
        {
            checkEmail = false;
            //objLeaveApplicationEventData.InsertLeaveApplicationDetailsInEmailTrigger(LeaveApplication_Id, strFromEmailId, EmployeeEamilId, strEmailIdReportingTo, rm.GetString("email_YourLeaveApplicationFor", ci) + " - " + lblFromDate.Text + " - " + lblToDate.Text + " | " + Status, mailMessage.Body.ToString(), "", "LeaveSanction");
        }
    }
    #endregion
    #region PermissionSanction & Bulk
    public void BindPermissionSanction(string isload)
    {
        string strStatus = string.Empty;
        string strScript = string.Empty;
        if (Convert.ToString(Session["UserGroupName"]) == "SuperAdmin" || Convert.ToString(Session["HasSpecialRights"]) == "True")
            dtPermissionSanctionView = objPermissionEventData.GetPermissionSanctionDetailsForSuperAdmin(Convert.ToInt32(Session["EmpAutoID"]), Convert.ToString(Session["LevelId"]), Convert.ToString(Session["Status"]), Convert.ToString(Session["SanFromDate"]), Convert.ToString(Session["SanToDate"]), Convert.ToString(Session["SanSwipeCardNo"]), Convert.ToString(Session["SanEmployeeName"]), Convert.ToString(Session["SanEmployeeCodeId"]), Convert.ToString(Session["UserGroupName"]), Convert.ToInt16(Session["parentLevelId"]), Convert.ToInt16(Session["SanEmpCategory"]), Convert.ToInt16(Session["SanEmpType"]));
        else
            dtPermissionSanctionView = objPermissionEventData.GetPermissionSanctionDetails(Convert.ToInt32(Session["EmpAutoId"]), Convert.ToString(Session["LevelId"]), Convert.ToString(Session["Status"]), Convert.ToString(Session["SanFromDate"]), Convert.ToString(Session["SanToDate"]), Convert.ToString(Session["SanSwipeCardNo"]), Convert.ToString(Session["SanEmployeeName"]), Convert.ToString(Session["SanEmployeeCodeId"]), Convert.ToString(Session["UserGroupName"]), Convert.ToInt16(Session["parentLevelId"]), Convert.ToInt16(Session["SanEmpCategory"]), Convert.ToInt16(Session["SanEmpType"]));
        if (dtPermissionSanctionView.Rows.Count > 0)
        {
            if (Convert.ToString(Session["Status"]) == "All" || Convert.ToString(Session["Status"]) == "Approved" || Convert.ToString(Session["Status"]) == "Rejected")
            {
                gdPermissionSanctionView.DataSource = dtPermissionSanctionView;
                gdPermissionSanctionView.DataBind();
                Session["SanctionType"] = "Permission";
                LoadDiv("PermissionSanction");
            }
            else if (Convert.ToString(Session["Status"]) == "Forwarded" || Convert.ToString(Session["Status"]) == "Pending")
            {
                gdPermissionSanctionViewBulk.DataSource = dtPermissionSanctionView;
                gdPermissionSanctionViewBulk.DataBind();
                Session["SanctionType"] = "PermissionBulk";
                LoadDiv("PermissionSanctionBulk");
            }
        }
        else
        {
            if (isload == "Unload")
            {
                Message(rm.GetString("Alert_Thereisnorecord", ci));
            }
            LoadDiv("clear");
            return;
        }
    }
    public string CalculateNumberOfHoursApplied(string startTime, string EndTime)
    {
        TimeSpan tsDiff = new TimeSpan();
        DateTime dtmIn = DateTime.Parse(startTime);
        DateTime dtmOut = DateTime.Parse(EndTime);
        tsDiff = dtmOut.Subtract(dtmIn);
        string s = tsDiff.ToString();
        int sReturn = s.LastIndexOf(':');
        string RemainHours = s.Remove(sReturn);
        return (RemainHours);
    }
    private void SendMailToApplicantPermission(string EmployeeEamilId, string strEmailIdReportingTo, string strEmailIdSanctionAuthority, string Status, string Remarks, string EmployeeCodeId, string TotalHours, string levelName, string employeename)
    {
        MailMessage mailMessage = new MailMessage();
        string scriptText;
        DataTable dtTableScript = new DataTable();
        string strFromEmailId = string.Empty;
        try
        {
            dtTableScript = objLeaveApplicationEventData.GetEmailScripts("Permission Application Sanction By Reporting to Person");
            if (dtTableScript.Rows.Count > 0)
            {
                scriptText = Convert.ToString(dtTableScript.Rows[0]["ScriptText"]);
                // As per elite partner requisition, mail should be trigger from admin id, whatever we configured in setting page.
                //25-Dec-2019 02:06 PM
                //if (Session["loginEmailId"] != null && Convert.ToString(Session["loginEmailId"]) != string.Empty)
                //{
                //    mailMessage.From = new MailAddress(Session["loginEmailId"].ToString());
                //    strFromEmailId = Convert.ToString(Session["loginEmailId"]);
                //}
                //else
                //{
                mailMessage.From = new MailAddress(ConfigurationManager.AppSettings.Get("FromId"));
                strFromEmailId = Convert.ToString(ConfigurationManager.AppSettings.Get("FromId"));
                //}
                if (Status == "Forwarded")
                {
                    if (strEmailIdSanctionAuthority != string.Empty)
                        mailMessage.To.Add(new MailAddress(strEmailIdSanctionAuthority));
                    if (EmployeeEamilId != string.Empty)
                        mailMessage.CC.Add(new MailAddress(EmployeeEamilId));
                }
                if (Session["loginEmailId"] != null && Session["loginEmailId"].ToString() != string.Empty)
                {
                    if (strEmailIdSanctionAuthority != strEmailIdReportingTo)
                    {
                        if (Status != "Forwarded")
                        {
                            if (Session["loginEmailId"].ToString() == strEmailIdSanctionAuthority)
                            {
                                if (EmployeeEamilId != string.Empty)
                                    mailMessage.To.Add(new MailAddress(EmployeeEamilId));
                                if (strEmailIdReportingTo != string.Empty)
                                    mailMessage.CC.Add(new MailAddress(strEmailIdReportingTo));
                            }
                            if (Session["loginEmailId"].ToString() == strEmailIdReportingTo)
                            {
                                if (EmployeeEamilId != string.Empty)
                                    mailMessage.To.Add(new MailAddress(EmployeeEamilId));
                            }
                        }
                    }
                    else
                    {
                        if (Status != "Forwarded")
                            if (EmployeeEamilId != string.Empty)
                                mailMessage.To.Add(new MailAddress(EmployeeEamilId));
                    }
                }
                else
                {
                    if (Status != "Forwarded")
                        if (EmployeeEamilId != string.Empty)
                            mailMessage.To.Add(new MailAddress(EmployeeEamilId));
                }
                switch (Status)
                {
                    case "Approved":
                        Status = rm.GetString("btn_Approved", ci);
                        break;
                    case "Forwarded":
                        Status = rm.GetString("btn_Forwarded", ci);
                        break;
                    case "Pending":
                        Status = rm.GetString("btn_Pending", ci);
                        break;
                    case "Rejected":
                        Status = rm.GetString("btn_Reject", ci);
                        break;
                }
                mailMessage.Subject = rm.GetString("email_YourPermissionApplicationFor", ci) + " - " + lblPermissionDate + " | " + Employee_Code_Id + " - " + EmployeeName + " | " + Status;
                mailMessage.Body = scriptText.Replace("<<lblPermissionSanction>>", rm.GetString("email_PermissionForm", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<lblEmployeeId>>", rm.GetString("email_EmployeeId", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<EmployeeId>>", EmployeeCodeId);
                mailMessage.Body = mailMessage.Body.Replace("<<lblEmployeeName>>", rm.GetString("email_EmployeeName", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<EmployeeName>>", employeename);
                mailMessage.Body = mailMessage.Body.Replace("<<lblPermissionDate>>", rm.GetString("Permission_PermissionDate", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<PermissionDate>>", lblPermissionDate);
                mailMessage.Body = mailMessage.Body.Replace("<<lblNumberOfHoursApplied>>", rm.GetString("email_NumberOfHoursApplied", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<NumberOfHoursApplied>>", TotalHours);
                mailMessage.Body = mailMessage.Body.Replace("<<lblPermission>>", rm.GetString("Dash_Permission", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<lblFromTime>>", rm.GetString("email_FromDate", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<FromTime>>", lblPermissionFromTime);
                mailMessage.Body = mailMessage.Body.Replace("<<lblToTime>>", rm.GetString("email_ToDate", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<ToTime>>", lblPermissionToTime);
                mailMessage.Body = mailMessage.Body.Replace("<<lblStatus>>", rm.GetString("email_Status", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<Status>>", Status);
                mailMessage.Body = mailMessage.Body.Replace("<<lblReason>>", rm.GetString("email_Reason", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<Reason>>", Remarks);
                mailMessage.Body = mailMessage.Body.Replace("<<lblRemarks>>", rm.GetString("email_Remarks", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<Remarks>>", "Ok");
                if (Status == "Forwarded" || Status == "Pending")
                    mailMessage.Body = mailMessage.Body.Replace("<<LinkData>>", Convert.ToString(Session["HostServerURL"]) + "?Permission_Id=" + Convert.ToString(Permission_Id) + "&LevelId=" + Session["LevelId"] + "&Status=" + Status + "&ApprovalType=Permission");
                else
                {
                    string strReplaceText = "<a href=<<LinkData>>><font face=\"Arial\" size=\"2\">Click here for approval</font>";
                    mailMessage.Body = mailMessage.Body.Replace(strReplaceText, string.Empty);
                }
                objClassCommon.SendMail(mailMessage);
            }
            else
            {
                checkEmail = false;
            }
        }
        catch
        {
            objLeaveApplicationEventData.InsertLeaveApplicationDetailsInEmailTrigger(Permission_Id, strFromEmailId, EmployeeEamilId, strEmailIdReportingTo, rm.GetString("email_YourPermissionApplicationFor", ci) + " - " + lblPermissionDate + " | " + Status, mailMessage.Body.ToString(), "", "PermissionSanction");
            checkEmail = false;
        }
    }
    #endregion
    #region Onduty
    public void BindOndutySanctionDetails(string isLoad)
    {
        string strStatus = string.Empty;
        string strScript = string.Empty;
        if (Convert.ToString(Session["UserGroupName"]) == "SuperAdmin" || Convert.ToString(Session["HasSpecialRights"]) == "True")
            dtManualEntrySanctionView = objManualEntryEventData.GetOnDutyEntrySanctionForSuperAdmin(Convert.ToInt32(Session["EmpAutoId"]), Convert.ToString(Session["LevelId"]), Convert.ToString(Session["Status"]), Convert.ToString(Session["SanEmployeeCodeId"]), Convert.ToString(Session["SanEmployeeName"]), Convert.ToInt16(Session["SanEmpCategory"]), Convert.ToInt16(Session["SanEmpType"]), Convert.ToString(Session["SanFromDate"]), Convert.ToString(Session["SanToDate"]), Convert.ToString(Session["SanSwipeCardNo"]), Convert.ToString(Session["UserGroupName"]), Convert.ToInt16(Session["parentLevelId"]));
        else
            dtManualEntrySanctionView = objManualEntryEventData.GetOnDutySanctionForUser(Convert.ToInt32(Session["EmpAutoId"]), Convert.ToString(Session["LevelId"]), Convert.ToString(Session["Status"]), Convert.ToString(Session["SanEmployeeCodeId"]), Convert.ToString(Session["SanEmployeeName"]), Convert.ToInt16(Session["SanEmpCategory"]), Convert.ToInt16(Session["SanEmpType"]), Convert.ToString(Session["SanFromDate"]), Convert.ToString(Session["SanToDate"]), Convert.ToString(Session["SanSwipeCardNo"]), Convert.ToString(Session["UserGroupName"]), Convert.ToInt16(Session["parentLevelId"]));
        if (dtManualEntrySanctionView.Rows.Count > 0)
        {
            if (Convert.ToString(Session["Status"]) == "All" || Convert.ToString(Session["Status"]) == "Approved" || Convert.ToString(Session["Status"]) == "Rejected")
            {
                gdOndutySanctionView.DataSource = dtManualEntrySanctionView;
                gdOndutySanctionView.DataBind();
                Session["SanctionType"] = "Onduty";
                LoadDiv("OndutySanction");
            }
            else if (Convert.ToString(Session["Status"]) == "Forwarded" || Convert.ToString(Session["Status"]) == "Pending")
            {
                gdOndutySanctionViewBulk.DataSource = dtManualEntrySanctionView;
                gdOndutySanctionViewBulk.DataBind();
                Session["SanctionType"] = "OndutyBulk";
                LoadDiv("OndutySanctionBulk");
            }
        }
        else
        {
            if (isLoad == "Unload")
            {
                Message(rm.GetString("Alert_Thereisnorecord", ci));
            }
            LoadDiv("clear");
            return;
        }
    }
    public void BindTimeSheetEntry(string isLoad)
    {
        dtManualEntrySanctionView = objtimeSheet.GetTimesheetEntryDetailsForSanction
            (
                Convert.ToInt32(Session["EmpAutoId"]),
                Convert.ToString(Session["LevelId"]),
                Convert.ToString(Session["Status"]),
                Convert.ToString(Session["SanEmployeeCodeId"]),
                Convert.ToString(Session["SanEmployeeName"]),
                Convert.ToInt16(Session["SanEmpCategory"]),
                Convert.ToInt16(Session["SanEmpType"]),
                Convert.ToString(Session["SanFromDate"]),
                Convert.ToString(Session["SanToDate"]),
                Convert.ToString(Session["UserGroupName"]),
                Convert.ToInt16(Session["parentLevelId"])
            );
        if (dtManualEntrySanctionView.Rows.Count > 0)
        {
            grvTimesheetEntry.DataSource = dtManualEntrySanctionView;
            grvTimesheetEntry.DataBind();
            Session["SanctionType"] = "Timesheet";
            LoadDiv("Timesheet");
        }
        else
        {
            if (isLoad == "Unload")
            {
                Message(rm.GetString("Alert_Thereisnorecord", ci));
            }
            LoadDiv("clear");
            return;
        }
    }
    protected void UpdatedManualTimeEntryStatus(string Status)
    {
        string strEmployeeName = string.Empty;
        string strRemarks = string.Empty;
        DataTable dtManual = new DataTable();
        dtManual = (DataTable)Session["dtSanctionView"];
        strRemarks = "Ok";
        intCount = dtManual.Rows.Count;
        Isprocessedrecord = false;
        if (dtManual.Rows.Count > 0)
        {
            DataTable dtDataToBeUpdated = new DataTable();
            dtDataToBeUpdated = dtManual.DefaultView.ToTable();
            if (dtDataToBeUpdated.Rows.Count > 0)
            {
                CheckGrid = true;
                StringWriter strXMLData = new StringWriter();
                dtDataToBeUpdated.WriteXml(strXMLData);
                if (Convert.ToString(Session["UserGroupName"]) == "SuperAdmin")
                {
                    statusProcess = true;
                    Session["dtSanctionView"] = null;
                    InsertCount = InsertCount + 1;
                    objManualEntryEventData.UpdateOndutyEntrySanction_Approvel(Convert.ToInt32(gintManualTimeEntryId), Status, strRemarks, Convert.ToInt32(Session["EmpAutoId"]));
                    objManualEntryEventData.UpdateOnDutyApplicationConversation(gintManualTimeEntryId, Status, strRemarks, Convert.ToInt32(Session["EmpAutoId"]));
                }
                else
                {
                    statusProcess = true;
                    Session["dtSanctionView"] = null;
                    InsertCount = InsertCount + 1;
                    objManualEntryEventData.UpdateOndutyEntrySanction_Approvel(Convert.ToInt32(gintManualTimeEntryId), Status, strRemarks, Convert.ToInt32(Session["EmpAutoId"]));
                    objManualEntryEventData.UpdateOnDutyApplicationConversation(gintManualTimeEntryId, Status, strRemarks, Convert.ToInt32(Session["EmpAutoId"]));
                }
            }
        }
    }
    private void SendMailOnduty(int OnDutyID, int LevelID, string strEmployeeEmailId, string ToMailId, string SanctionMailId, string FromDate, string FromTime, string ToDate, string ToTime, string ApplicationDate, string EmployeeName, string Employee_Code_Id, string strReason, string strlevelName, string OndutyStatus)
    {
        string strFromEmailId = string.Empty;
        MailMessage mailMessage = new MailMessage();
        System.Net.Mime.ContentType loTextType = new System.Net.Mime.ContentType("text/plain");
        System.Net.Mime.ContentType loHTMLType = new System.Net.Mime.ContentType("text/html");
        AlternateView loHTMLView = null;
        try
        {
            string scriptText;
            DataTable dtTableScript = new DataTable();
            string ScriptType = "Onduty Application Modify";
            dtTableScript = objLeaveApplicationEventData.GetEmailScripts(ScriptType);
            if (dtTableScript.Rows.Count > 0)
            {
                scriptText = Convert.ToString(dtTableScript.Rows[0]["ScriptText"]);
                //if (Session["loginEmailId"] != null && Convert.ToString(Session["loginEmailId"]) != string.Empty)
                //{
                //    mailMessage.From = new MailAddress(Convert.ToString(Session["loginEmailId"]));
                //    strFromEmailId = Convert.ToString(Session["loginEmailId"]);
                //}
                //else
                //{
                mailMessage.From = new MailAddress(ConfigurationManager.AppSettings.Get("FromId"));
                strFromEmailId = Convert.ToString(ConfigurationManager.AppSettings.Get("FromId"));
                //}
                if (OndutyStatus == "Forwarded")
                {
                    if (SanctionMailId != string.Empty)
                        mailMessage.To.Add(new MailAddress(SanctionMailId));
                    if (strEmployeeEmailId != string.Empty)
                        mailMessage.CC.Add(new MailAddress(strEmployeeEmailId));
                }
                if (Session["loginEmailId"] != null && Session["loginEmailId"].ToString() != string.Empty)
                {
                    if (SanctionMailId != strEmailIdReportingTo)
                    {
                        if (OndutyStatus != "Forwarded")
                        {
                            if (Session["loginEmailId"].ToString() == SanctionMailId)
                            {
                                if (strEmployeeEmailId != string.Empty)
                                    mailMessage.To.Add(new MailAddress(strEmployeeEmailId));
                                if (strEmailIdReportingTo != string.Empty)
                                    mailMessage.CC.Add(new MailAddress(strEmailIdReportingTo));
                            }
                            if (Session["loginEmailId"].ToString() == strEmailIdReportingTo)
                                if (strEmployeeEmailId != string.Empty)
                                    mailMessage.To.Add(new MailAddress(strEmployeeEmailId));
                        }
                    }
                    else
                    {
                        if (OndutyStatus != "Forwarded")
                            if (strEmployeeEmailId != string.Empty)
                                mailMessage.To.Add(new MailAddress(strEmployeeEmailId));
                    }
                }
                else
                {
                    if (OndutyStatus != "Forwarded")
                        if (strEmployeeEmailId != string.Empty)
                            mailMessage.To.Add(new MailAddress(strEmployeeEmailId));
                }
                if (Status == "Approved")
                {
                    DataSet dsCCEmailIds = new DataSet();
                    DataSet dsSanctionView = new DataSet();
                    dsSanctionView = objManualEntryEventData.SelectODEntryById(gintManualTimeEntryId);
                    dtSanctionView = dsSanctionView.Tables[0];
                    dsCCEmailIds = objCCGroup.GetCCEmailIds(Convert.ToInt16(dtSanctionView.Rows[0]["levelid"].ToString()), Convert.ToInt16(dtSanctionView.Rows[0]["DesignationID"].ToString()), "OD");
                    if (dsCCEmailIds != null)
                    {
                        if (dsCCEmailIds.Tables[0].Rows.Count > 0)
                        {
                            foreach (DataRow drCcEmailId in dsCCEmailIds.Tables[0].Rows)
                            {
                                MailAddressCollection MailAddrCollectionCC = mailMessage.CC;
                                if (drCcEmailId["EmailId"].ToString() != string.Empty)
                                {
                                    MailAddress newCC = new MailAddress(drCcEmailId["EmailId"].ToString());
                                    MailAddrCollectionCC.Add(newCC);
                                }
                            }
                        }
                    }
                }
                TimeFormatMail = Convert.ToString(Session["ITimeFormat"]);
                if (TimeFormatMail == "HH:mm")
                    TimeFormatMail = "HH:mm";
                else
                    TimeFormatMail = "hh:mm tt";
                mailMessage.Subject = rm.GetString("email_YourOndutyApplicationFor", ci) + " - " + ApplicationDate + " | " + Employee_Code_Id + " - " + EmployeeName + " | " + strlevelName + " - " + OndutyStatus;
                mailMessage.Body = scriptText.Replace("<<lblOndutyForm>>", rm.GetString("email_OndutyApplicationForm", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<ltr_rtl>>", rm.GetString("Direction", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<lblEmployeeID>>", rm.GetString("email_EmployeeId", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<EmployeeID>>", Employee_Code_Id);
                mailMessage.Body = mailMessage.Body.Replace("<<lblEmployeeName>>", rm.GetString("email_EmployeeName", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<EmployeeName>>", EmployeeName);
                mailMessage.Body = mailMessage.Body.Replace("<<lblApplicationDate>>", rm.GetString("ODEntry_ODEntryDate", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<ApplicationDate>>", ApplicationDate);
                mailMessage.Body = mailMessage.Body.Replace("<<lblODDate>>", rm.GetString("OnDutyDate", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<lblFromDate>>", rm.GetString("email_FromDate", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<FromDate>>", FromDate + " " + Convert.ToDateTime(FromTime).ToString(TimeFormatMail));
                mailMessage.Body = mailMessage.Body.Replace("<<lblToDate>>", rm.GetString("email_ToDate", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<ToDate>>", ToDate + " " + Convert.ToDateTime(ToTime).ToString(TimeFormatMail));
                mailMessage.Body = mailMessage.Body.Replace("<<lblStatus>>", rm.GetString("email_Status", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<Status>>", OndutyStatus);
                mailMessage.Body = mailMessage.Body.Replace("<<lblReason>>", rm.GetString("email_Reason", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<Reason>>", strReason);
                mailMessage.Body = mailMessage.Body.Replace("<<lblRemarks>>", rm.GetString("email_Remarks", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<Remarks>>", "OK");
                if (OndutyStatus == "Forwarded" || OndutyStatus == "Pending")
                    mailMessage.Body = mailMessage.Body.Replace("<<LinkData>>", Convert.ToString(Session["HostServerURL"]) + "?ODID=" + Convert.ToString(OnDutyID) + "&LevelId=" + LevelID + "&Status=" + OndutyStatus + "&ApprovalType=Onduty&ParentID=" + Convert.ToString(Session["parentLevelId"]) + "");
                else
                {
                    string strReplaceText = "<font face=\"Arial\" size=\"2\"><a href=\"<<LinkData>>\">Click here for approval </a></font>";
                    mailMessage.Body = mailMessage.Body.Replace(strReplaceText, string.Empty);
                }
                objClassCommon.SendMail(mailMessage);
            }
            else
            {
                blnCheckEmail = false;
            }
        }
        catch
        {
            blnCheckEmail = false;
        }
    }
    #endregion
    #region General
    public DateTime CurrentMonthStartDate()
    {
        CurrentDate = (DateTime.Now);
        CurrentDate = CurrentDate.AddDays(-(CurrentDate.AddDays(-1).Day));
        CurrentDate = CurrentDate.AddMonths(-1);
        return CurrentDate;
    }
    public DateTime NextMonthEndDate()
    {
        CurrentDate = (DateTime.Now);
        CurrentDate = CurrentDate.AddMonths(1);
        month = CurrentDate.Month;
        year = CurrentDate.Year;
        TotalDays = System.DateTime.DaysInMonth(year, month);
        date = CurrentDate.Day;
        date = TotalDays - date;
        CurrentDate = CurrentDate.AddDays(date);
        return CurrentDate;
    }
    public void CompareDate(object s, ServerValidateEventArgs e)
    {
        try
        {
            gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
            strFromDateTime = objClassCommon.DateTimeConvertion((gstrDateFormat), txtFromDate.Text, "D");
            strToDateTime = objClassCommon.DateTimeConvertion((gstrDateFormat), txtToDate.Text, "D");
            DateTime dtToDate = DateTime.Parse(strToDateTime);
            DateTime dtFromDate = DateTime.Parse(strFromDateTime);
            TimeSpan diff = dtToDate.Subtract(dtFromDate);
            int day = diff.Days;
            if (day >= 0)
                e.IsValid = true;
            else
            {
                base.Message(rm.GetString("Msg_GrearterThanFrmDate", ci));
                e.IsValid = false;
            }
        }
        catch
        {
        }
    }
    public void CompareCurrentdate(object s, ServerValidateEventArgs e)
    {
        try
        {
            gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
            strFromDateTime = objClassCommon.DateTimeConvertion((gstrDateFormat), txtFromDate.Text, "D");
            DateTime dtCurrentDate = DateTime.Now;
            DateTime dtFromDate = DateTime.Parse(strFromDateTime);
            TimeSpan diff = dtFromDate.Subtract(dtCurrentDate);
            int day = diff.Days;
            if (day >= 0)
                e.IsValid = true;
            else
                e.IsValid = false;
        }
        catch
        {
        }
    }
    public void CompareTodate(object s, ServerValidateEventArgs e)
    {
        try
        {
            gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
            strToDateTime = objClassCommon.DateTimeConvertion((gstrDateFormat), txtToDate.Text, "D");
            DateTime dtCurrentDate = DateTime.Now;
            DateTime dtFromDate = DateTime.Parse(strToDateTime);
            TimeSpan diff = dtFromDate.Subtract(dtCurrentDate);
            int day = diff.Days;
            if (day >= 0)
                e.IsValid = true;
            else
                e.IsValid = false;
        }
        catch
        {
        }
    }
    public int getParentCompany(int iEmployeeLevelID)
    {
        org_levelsEventData getOrg = new org_levelsEventData();
        getOrg.GetOrgParentLevels_FromID(iEmployeeLevelID);
        DataSet ds_getOrg = new DataSet();
        ds_getOrg = getOrg.GetOrgParentLevels();
        int iCompanyID = 0;
        if (ds_getOrg != null)
            if (ds_getOrg.Tables[0].Rows.Count > 0)
                iCompanyID = Convert.ToInt32(ds_getOrg.Tables[0].Rows[0]["LevelID"].ToString());
        return iCompanyID;
    }
    public string GetApprovalStatus(int intCompanyId, string strModule)
    {
        int approvalSettingsPageExists = 0;
        //Checking grade module is available or not and changed the id value from 110 to 228
        approvalSettingsPageExists = objClassCommon.CheckPageExistsInLicense(228);
        string strStatus = string.Empty;
        if (approvalSettingsPageExists == 1)
        {
            DataSet dsApprovalSettings = new DataSet();
            ShiftEvenData objShift = new ShiftEvenData();
            dsApprovalSettings = objShift.SelectApprovalSettings(intCompanyId);
            if (dsApprovalSettings != null)
                if (dsApprovalSettings.Tables.Count > 0)
                    if (dsApprovalSettings.Tables[0].Rows.Count > 0)
                    {
                        if (Convert.ToBoolean(dsApprovalSettings.Tables[0].Rows[0][strModule]) == false)
                            strStatus = "ApprovalNotRequired";
                        else
                            strStatus = "ApprovalRequired";
                    }
                    else
                        strStatus = "NotDefined";
        }
        else
            strStatus = "ApprovalRequired";
        return strStatus;
    }
    private void LoadStrings(CultureInfo ci)
    {
        lbl_From.Text = rm.GetString("email_FromDate", ci);
        lbl_Status.Text = rm.GetString("email_Status", ci);
        lbl_To.Text = rm.GetString("email_ToDate", ci);
        cus_ComDate.ErrorMessage = rm.GetString("Msg_GrearterThanFrmDate", ci);
        lbl_Header.Text = rm.GetString("Transaction_Approvals", ci);
        lbl_IndicatesMandatoryFields.Text = rm.GetString("IndicatesMandatoryFields", ci);
        btn_View.Text = "&nbsp;&nbsp;" + rm.GetString("btn_View", ci);
        lbl_EmployeeName.Text = rm.GetString("email_EmployeeName", ci);
        lbl_EmployeeId.Text = rm.GetString("email_EmployeeId", ci);
        lblEmpSwipe.Text = rm.GetString("TerminalDataType_Card_No", ci);
        ddlStatus.Items[0].Text = rm.GetString("ExportData_All", ci);
        ddlStatus.Items[1].Text = rm.GetString("btn_Approved", ci);
        ddlStatus.Items[2].Text = rm.GetString("btn_Forwarded", ci);
        ddlStatus.Items[3].Text = rm.GetString("btn_Pending", ci);
        ddlStatus.Items[4].Text = rm.GetString("btn_Reject", ci);
        lblEmpCategory.Text = rm.GetString("Master_Category", ci);
        lblEmpType.Text = rm.GetString("Master_Type", ci);
        lblFilter.Text = rm.GetString("lblFilter", ci);
        gdLeaveSanctionView.Columns[0].Caption = rm.GetString("email_EmployeeId", ci);
        gdLeaveSanctionView.Columns[1].Caption = rm.GetString("email_EmployeeName", ci);
        gdLeaveSanctionView.Columns[2].Caption = rm.GetString("LeaveApplication_LeaveApplicationDate", ci);
        gdLeaveSanctionView.Columns[3].Caption = rm.GetString("Report_Duration", ci);
        gdLeaveSanctionView.Columns[4].Caption = rm.GetString("email_Status", ci);
        gdLeaveSanctionViewBulk.Columns[1].Caption = rm.GetString("email_EmployeeId", ci);
        gdLeaveSanctionViewBulk.Columns[2].Caption = rm.GetString("email_EmployeeName", ci);
        gdLeaveSanctionViewBulk.Columns[3].Caption = rm.GetString("LeaveApplication_LeaveApplicationDate", ci);
        gdLeaveSanctionViewBulk.Columns[4].Caption = rm.GetString("Report_Duration", ci);
        gdLeaveSanctionViewBulk.Columns[5].Caption = rm.GetString("Type_Of_Leave", ci);
        gdLeaveSanctionViewBulk.Columns[6].Caption = rm.GetString("email_Status", ci);
        gdPermissionSanctionView.Columns[0].Caption = rm.GetString("email_EmployeeId", ci);
        gdPermissionSanctionView.Columns[1].Caption = rm.GetString("email_EmployeeName", ci);
        gdPermissionSanctionView.Columns[2].Caption = rm.GetString("LeaveApplication_LeaveApplicationDate", ci);
        gdPermissionSanctionView.Columns[3].Caption = rm.GetString("Report_Duration", ci);
        gdPermissionSanctionView.Columns[4].Caption = rm.GetString("email_Status", ci);
        gdPermissionSanctionViewBulk.Columns[1].Caption = rm.GetString("email_EmployeeId", ci);
        gdPermissionSanctionViewBulk.Columns[2].Caption = rm.GetString("email_EmployeeName", ci);
        gdPermissionSanctionViewBulk.Columns[3].Caption = rm.GetString("LeaveApplication_LeaveApplicationDate", ci);
        gdPermissionSanctionViewBulk.Columns[4].Caption = rm.GetString("Report_Duration", ci);
        gdPermissionSanctionViewBulk.Columns[5].Caption = rm.GetString("email_Status", ci);
        gdOndutySanctionView.Columns[1].Caption = rm.GetString("email_EmployeeId", ci);
        gdOndutySanctionView.Columns[2].Caption = rm.GetString("email_EmployeeName", ci);
        gdOndutySanctionView.Columns[3].Caption = rm.GetString("ManualTimeEntry_ManualTimeEntryDate", ci);
        gdOndutySanctionView.Columns[4].Caption = rm.GetString("OnDuty_InDate", ci);
        gdOndutySanctionView.Columns[5].Caption = rm.GetString("OnDuty_InTime", ci);
        gdOndutySanctionView.Columns[6].Caption = rm.GetString("OnDuty_OutDate", ci);
        gdOndutySanctionView.Columns[7].Caption = rm.GetString("OnDuty_OutTime", ci);
        gdOndutySanctionView.Columns[8].Caption = rm.GetString("email_Reason", ci);
        gdOndutySanctionView.Columns[9].Caption = rm.GetString("email_Status", ci);
        gdOndutySanctionViewBulk.Columns[1].Caption = rm.GetString("email_EmployeeId", ci);
        gdOndutySanctionViewBulk.Columns[2].Caption = rm.GetString("email_EmployeeName", ci);
        gdOndutySanctionViewBulk.Columns[3].Caption = rm.GetString("ManualTimeEntry_ManualTimeEntryDate", ci);
        gdOndutySanctionViewBulk.Columns[4].Caption = rm.GetString("OnDuty_InDate", ci);
        gdOndutySanctionViewBulk.Columns[5].Caption = rm.GetString("OnDuty_InTime", ci);
        gdOndutySanctionViewBulk.Columns[6].Caption = rm.GetString("OnDuty_OutDate", ci);
        gdOndutySanctionViewBulk.Columns[7].Caption = rm.GetString("OnDuty_OutTime", ci);
        gdOndutySanctionViewBulk.Columns[8].Caption = rm.GetString("email_Status", ci);
        gdOndutySanctionViewBulk.Columns[9].Caption = rm.GetString("email_Reason", ci);
        rbLeaveApplication.Text = rm.GetString("LeaveApplication_Leave", ci);
        rbPermission.Text = rm.GetString("Dash_Permission", ci);
        rbOnduty.Text = rm.GetString("Dash_OnDuty", ci);
        lnkbtnTimesheetApproval.Text = btnSaveLeaveSanction.Text = "&nbsp;&nbsp;" + rm.GetString("Sanction_Approve", ci);
        btnSavePermission.Text = "&nbsp;&nbsp;" + rm.GetString("Sanction_Approve", ci);
        btnSaveOnduty.Text = "&nbsp;&nbsp;" + rm.GetString("Sanction_Approve", ci);
        btnReject.Text = lnkbtnTimesheetReject.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Reject", ci);
    }
    private void UserRights()
    {
        if (ViewState["vs_ds_Checkuser"] != null)
            ds_Checkuser = (DataSet)ViewState["vs_ds_Checkuser"];
        else
        {
            ds_Checkuser = objCheckUser.checkRights(248, Convert.ToInt32(Session["userGroup_Id"]), "viewPrv");
            ViewState["vs_ds_Checkuser"] = ds_Checkuser;
        }
        if (ds_Checkuser.Tables[0].Rows.Count == 0)
            Response.Redirect("TransactionLandingPage.aspx");
    }
    private void LoadDiv(string Values)
    {
        switch (Values)
        {
            case "LeaveSanction":
                #region LeaveSanction
                divLeaveSanction.Style.Add("display", "block");
                divLeaveSanctionBulk.Style.Add("display", "none");
                divPermissionSanction.Style.Add("display", "none");
                divPermissionSanctionBulk.Style.Add("display", "none");
                divOndutySanction.Style.Add("display", "none");
                divOndutySanctionBulk.Style.Add("display", "none");
                divTimesheet.Style.Add("display", "none");
                divMyProfile.Style.Add("display", "none");
                #endregion
                break;
            case "LeaveSanctionBulk":
                #region LeaveSanctionBulk
                divLeaveSanction.Style.Add("display", "none");
                divLeaveSanctionBulk.Style.Add("display", "block");
                divPermissionSanction.Style.Add("display", "none");
                divPermissionSanctionBulk.Style.Add("display", "none");
                divOndutySanction.Style.Add("display", "none");
                divOndutySanctionBulk.Style.Add("display", "none");
                divTimesheet.Style.Add("display", "none");
                divMyProfile.Style.Add("display", "none");
                #endregion
                break;
            case "PermissionSanction":
                #region PermissionSanction
                divLeaveSanction.Style.Add("display", "none");
                divLeaveSanctionBulk.Style.Add("display", "none");
                divPermissionSanction.Style.Add("display", "block");
                divPermissionSanctionBulk.Style.Add("display", "none");
                divOndutySanction.Style.Add("display", "none");
                divOndutySanctionBulk.Style.Add("display", "none");
                divTimesheet.Style.Add("display", "none");
                divMyProfile.Style.Add("display", "none");
                #endregion
                break;
            case "PermissionSanctionBulk":
                #region PermissionSanctionBulk
                divLeaveSanction.Style.Add("display", "none");
                divLeaveSanctionBulk.Style.Add("display", "none");
                divPermissionSanction.Style.Add("display", "none");
                divPermissionSanctionBulk.Style.Add("display", "block");
                divOndutySanctionBulk.Style.Add("display", "none");
                divTimesheet.Style.Add("display", "none");
                divMyProfile.Style.Add("display", "none");
                #endregion
                break;
            case "OndutySanction":
                #region OndutySanction
                divLeaveSanction.Style.Add("display", "none");
                divLeaveSanctionBulk.Style.Add("display", "none");
                divPermissionSanction.Style.Add("display", "none");
                divPermissionSanctionBulk.Style.Add("display", "none");
                divOndutySanction.Style.Add("display", "block");
                divOndutySanctionBulk.Style.Add("display", "none");
                divTimesheet.Style.Add("display", "none");
                divMyProfile.Style.Add("display", "none");
                #endregion
                break;
            case "OndutySanctionBulk":
                #region OndutySanctionBulk
                divLeaveSanction.Style.Add("display", "none");
                divLeaveSanctionBulk.Style.Add("display", "none");
                divPermissionSanction.Style.Add("display", "none");
                divPermissionSanctionBulk.Style.Add("display", "none");
                divOndutySanction.Style.Add("display", "none");
                divOndutySanctionBulk.Style.Add("display", "block");
                divTimesheet.Style.Add("display", "none");
                divMyProfile.Style.Add("display", "none");
                #endregion
                break;
            case "Timesheet":
                #region OndutySanctionBulk
                divLeaveSanction.Style.Add("display", "none");
                divLeaveSanctionBulk.Style.Add("display", "none");
                divPermissionSanction.Style.Add("display", "none");
                divPermissionSanctionBulk.Style.Add("display", "none");
                divOndutySanction.Style.Add("display", "none");
                divOndutySanctionBulk.Style.Add("display", "none");
                divTimesheet.Style.Add("display", "block");
                divMyProfile.Style.Add("display", "none");
                #endregion
                break;
            case "MyProfile":
                #region MyProfile
                divLeaveSanction.Style.Add("display", "none");
                divLeaveSanctionBulk.Style.Add("display", "none");
                divPermissionSanction.Style.Add("display", "none");
                divPermissionSanctionBulk.Style.Add("display", "none");
                divOndutySanction.Style.Add("display", "none");
                divOndutySanctionBulk.Style.Add("display", "none");
                divTimesheet.Style.Add("display", "none");
                divMyProfile.Style.Add("display", "block");
                #endregion
                break;
            case "clear":
                #region Clear
                divLeaveSanction.Style.Add("display", "none");
                divLeaveSanctionBulk.Style.Add("display", "none");
                divPermissionSanction.Style.Add("display", "none");
                divPermissionSanctionBulk.Style.Add("display", "none");
                divOndutySanction.Style.Add("display", "none");
                divOndutySanctionBulk.Style.Add("display", "none");
                divTimesheet.Style.Add("display", "none");
                divMyProfile.Style.Add("display", "none");
                #endregion
                break;
        }
    }
    private void GetFilter()
    {
        ddlStatus.SelectedValue = Convert.ToString(Session["Status"]);
        txtFromDate.Text = Convert.ToString(Session["SanFromDateFormat"]);
        txtToDate.Text = Convert.ToString(Session["SanTodateFormat"]);
        txtSwipeCard.Text = Convert.ToString(Session["SanSwipeCardNo"]);
        txt_EmpName.Text = Convert.ToString(Session["SanEmployeeName"]);
        txtEmployeeId.Text = Convert.ToString(Session["SanEmployeeCodeId"]);
        ddlEmpCatagory.SelectedValue = Convert.ToString(Session["SanEmpCategory"]);
        ddlEmpType.SelectedValue = Convert.ToString(Session["SanEmpType"]);
    }
    #endregion
    #region EmployeeCategoryandType
    private void BindingEmployeeCategoryandType()
    {
        // employee category binding
        DataSet dsCategory = new DataSet();
        dsCategory = objEmployee.SelectCategoryDetailsEmployee("");
        if (dsCategory != null)
        {
            if (dsCategory.Tables[0].Rows.Count > 0)
            {
                ddlEmpCatagory.DataSource = dsCategory;
                ddlEmpCatagory.DataTextField = "CategoryName";
                ddlEmpCatagory.DataValueField = "CategoryId";
                ddlEmpCatagory.DataBind();
            }
            dsCategory.Dispose();
            foreach (ListItem item in ddlEmpCatagory.Items)
            {
                item.Attributes.Add("title", item.Text);
            }
        }
        DataSet dsType = new DataSet();
        dsType = objEmployee.SelectTypeDetailsEmployee("");
        if (dsType != null)
        {
            if (dsType.Tables[0].Rows.Count > 0)
            {
                ddlEmpType.DataSource = dsType;
                ddlEmpType.DataTextField = "TypeName";
                ddlEmpType.DataValueField = "TypeId";
                ddlEmpType.DataBind();
            }
            dsType.Dispose();
            foreach (ListItem item in ddlEmpType.Items)
            {
                item.Attributes.Add("title", item.Text);
            }
        }
    }
    #endregion
    #region MyProfile Sanction
    public void bindMyProfileDetails(string isLoad)
    {
        Hashtable htable = new Hashtable();
        DataSet dsMyprofileSanctionView = new DataSet();
        htable.Add("@tag", "SS");
        htable.Add("@login_EmployeeID", Session["EmpAutoId"]);
        htable.Add("@LevelId", Session["LevelId"]);
        htable.Add("@Status", Session["Status"]);
        htable.Add("@EmployeeId", Session["SanEmployeeCodeId"]);
        htable.Add("@EmployeeName", Session["SanEmployeeName"]);
        htable.Add("@EmpCategory", Session["SanEmpCategory"]);
        htable.Add("@EmpType", Session["SanEmpType"]);
        htable.Add("@FromDate", Session["SanFromDate"]);
        htable.Add("@ToDate", Session["SanToDate"]);
        htable.Add("@UserGroupName", Session["UserGroupName"]);
        htable.Add("@ParentID", Session["parentLevelId"]);
        Session["SanctionType"] = "MyProfile";
        dsMyprofileSanctionView = objEmployee.InsertUpdateMyProfileDetails(htable);
        if (dsMyprofileSanctionView.Tables.Count > 0)
        {
            gdMyProfileSanctionView.DataSource = dsMyprofileSanctionView;
            gdMyProfileSanctionView.DataBind();
            LoadDiv("MyProfile");
        }
        else
        {
            if (isLoad == "Unload")
                Message(rm.GetString("Alert_Thereisnorecord", ci));
            LoadDiv("clear");
            return;
        }
    }
    #endregion
    #endregion
    #region Button Events
    private void CommonAlertMessage(string strStatus)
    {
        if (strStatus == "ApprovalNotRequired")
        {
            LoadDiv("clear");
            Message(rm.GetString("Alert_ApprovalNotRequiredforthiscompany", ci));
            return;
        }
        else if (strStatus == "NotDefined")
        {
            LoadDiv("clear");
            Message(rm.GetString("Alert_ApprovalSettingsnotdefinedforthiscompany", ci));
            return;
        }
    }
    protected void btn_View_Click(object sender, EventArgs e)
    {
        if (Page.IsValid == true)
        {
            gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
            int LevelId = Convert.ToInt32(Session["parentLevelId"]);
            string strScript = string.Empty;
            string strStatus = string.Empty;
            string strModule = string.Empty;
            Session["LeaveSanctionStatus"] = Convert.ToString(ddlStatus.SelectedValue);
            strScript = "";
            strScript = strScript + "<script language='javascript'>";
            if (Session["parentLevelId"] == null || Convert.ToInt32(Session["parentLevelId"]) == 0)
            {
                LoadDiv("clear");
                Message(rm.GetString("Alert_SelectCompany", ci));
                return;
            }
            intCompanyId = getParentCompany(Convert.ToInt32(Session["parentLevelId"]));
            Session["SanctionType"] = "";
            Session["LevelId"] = Convert.ToInt32(Session["parentLevelId"]);
            Session["Status"] = Convert.ToString(ddlStatus.SelectedValue);
            Session["SanFromDateFormat"] = txtFromDate.Text;
            Session["SanTodateFormat"] = txtToDate.Text;
            Session["SanFromDate"] = objClassCommon.DateConvertion(gstrDateFormat, txtFromDate.Text);
            Session["SanTodate"] = objClassCommon.DateConvertion(gstrDateFormat, txtToDate.Text);
            Session["SanSwipeCardNo"] = txtSwipeCard.Text;
            Session["SanEmployeeName"] = txt_EmpName.Text.Trim().Replace("'", "''");
            Session["SanEmployeeCodeId"] = txtEmployeeId.Text.Trim().Replace("'", "''");
            Session["SanEmpCategory"] = ddlEmpCatagory.SelectedValue;
            Session["SanEmpType"] = ddlEmpType.SelectedValue;
            if (rbLeaveApplication.Checked == true)
            {
                #region LeaveSanction
                strStatus = GetApprovalStatus(intCompanyId, "LeaveSanction");
                if (strStatus == "ApprovalNotRequired")
                {
                    LoadDiv("clear");
                    Message(rm.GetString("Alert_ApprovalNotRequiredforthiscompany", ci));
                    return;
                }
                else if (strStatus == "NotDefined")
                {
                    LoadDiv("clear");
                    Message(rm.GetString("Alert_ApprovalSettingsnotdefinedforthiscompany", ci));
                    return;
                }
                if (ddlStatus.SelectedItem.Text.ToString() == rm.GetString("ExportData_All", ci) || ddlStatus.SelectedItem.Text.ToString() == rm.GetString("btn_Approved", ci) || ddlStatus.SelectedItem.Text.ToString() == rm.GetString("btn_Reject", ci))
                {
                    Session["SanctionType"] = "Leave";
                    gdLeaveSanctionView.FilterExpression = "";
                    bindLeaveSanctionDetails("Unload");
                }
                else if (ddlStatus.SelectedItem.Text.ToString() == rm.GetString("btn_Forwarded", ci) || ddlStatus.SelectedItem.Text.ToString() == rm.GetString("btn_Pending", ci))
                {
                    Session["SanctionType"] = "LeaveBulk";
                    gdLeaveSanctionViewBulk.FilterExpression = "";
                    bindLeaveSanctionDetailsForBulkApproval("Unload");
                }
                #endregion
            }
            else if (rbPermission.Checked == true)
            {
                #region PermissionSanction
                strStatus = GetApprovalStatus(intCompanyId, "PermissionSanction");
                if (strStatus == "ApprovalNotRequired")
                {
                    LoadDiv("clear");
                    Message(rm.GetString("Alert_ApprovalNotRequiredforthiscompany", ci));
                    return;
                }
                else if (strStatus == "NotDefined")
                {
                    LoadDiv("clear");
                    Message(rm.GetString("Alert_ApprovalSettingsnotdefinedforthiscompany", ci));
                    return;
                }
                BindPermissionSanction("Unload");
                gdPermissionSanctionView.FilterExpression = "";
                gdPermissionSanctionViewBulk.FilterExpression = "";
                #endregion
            }
            else if (rbOnduty.Checked == true)
            {
                #region OndutySanction
                strStatus = GetApprovalStatus(intCompanyId, "ODEntry");
                if (strStatus == "ApprovalNotRequired")
                {
                    LoadDiv("clear");
                    Message(rm.GetString("Alert_ApprovalNotRequiredforthiscompany", ci));
                    return;
                }
                else if (strStatus == "NotDefined")
                {
                    LoadDiv("clear");
                    Message(rm.GetString("Alert_ApprovalSettingsnotdefinedforthiscompany", ci));
                    return;
                }
                BindOndutySanctionDetails("Unload");
                gdOndutySanctionView.FilterExpression = "";
                gdOndutySanctionViewBulk.FilterExpression = "";
                #endregion
            }
            else if (rbtnTimesheet.Checked == true)
            {
                #region TimesheetEntry
                //Todo: need to enable below comment
                //strStatus = GetApprovalStatus(intCompanyId, "TimeSheet");
                if (strStatus == "ApprovalNotRequired")
                {
                    LoadDiv("clear");
                    Message(rm.GetString("Alert_ApprovalNotRequiredforthiscompany", ci));
                    return;
                }
                else if (strStatus == "NotDefined")
                {
                    LoadDiv("clear");
                    Message(rm.GetString("Alert_ApprovalSettingsnotdefinedforthiscompany", ci));
                    return;
                }
                BindTimeSheetEntry("Unload");
                #endregion
            }
            else if (rbtnMyProfile.Checked == true)
            {
                #region MyProfileSanction
                if (strStatus == "ApprovalNotRequired")
                {
                    LoadDiv("clear");
                    Message(rm.GetString("Alert_ApprovalNotRequiredforthiscompany", ci));
                    return;
                }
                else if (strStatus == "NotDefined")
                {
                    LoadDiv("clear");
                    Message(rm.GetString("Alert_ApprovalSettingsnotdefinedforthiscompany", ci));
                    return;
                }
                bindMyProfileDetails("Unload");
                gdMyProfileSanctionView.FilterExpression = "";
                #endregion
            }
        }
    }
    protected void btnSaveLeaveSanction_Click(object sender, EventArgs e)
    {
        if (hdnSelectRow.Value != string.Empty && hdnSelectRow.Value != null)
        {
            #region SaveLeaveDetails
            NotSendedEmployeeCodeId = "";
            //Dim lnk as LinkButton = CType(sender, LinkButton)
            LinkButton lnkbtn = (LinkButton)sender;
            string[] test;
            string strTypeOfLeave = "";
            int YearSettingID = 0;
            test = commaStringToArray(hdnSelectRow.Value);
            DataTable dsCheckedItem;
            dsCheckedItem = (DataTable)Session["LeaveChecked"];
            for (int i = 0; i < test.Length; i++)
            {
                LeaveApplication_Id = Convert.ToInt32(test[i]);
                dtSanctionView = objLeaveApplicationEventData.GetLeaveApplicationByLeaveApplicationId(LeaveApplication_Id);
                SanctionViewDetails(LeaveApplication_Id);
                if (dtSanctionView.Rows.Count > 0)
                {
                    EmployeeName = Convert.ToString(dtSanctionView.Rows[0]["Employee_FirstName"]);
                    Employee_Id = Convert.ToInt32(dtSanctionView.Rows[0]["Employee_Id"]);
                    Employee_Code_Id = Convert.ToString(dtSanctionView.Rows[0]["Employee_Code_Id"]);
                    empEmailId = Convert.ToString(dtSanctionView.Rows[0]["EmailId"]);
                    strReason = Convert.ToString(dtSanctionView.Rows[0]["Reason"]);
                    gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
                    strLeaveApplicationDate = Convert.ToString(dtSanctionView.Rows[0]["Leave_ApplicationDate"]);
                    Leave_FromDate = objClassCommon.DateConvertion(gstrDateFormat, Convert.ToString(dtSanctionView.Rows[0]["Leave_FromDate"]));
                    Leave_FromDate = DateTime.Parse(Leave_FromDate).ToShortDateString();
                    Leave_ToDate = objClassCommon.DateConvertion(gstrDateFormat, Convert.ToString(dtSanctionView.Rows[0]["Leave_ToDate"]));
                    Leave_ToDate = DateTime.Parse(Leave_ToDate).ToShortDateString();
                    strNoOfDays = Convert.ToString(dtSanctionView.Rows[0]["NumberOfDays"]);
                    ViewState["LevelName"] = Convert.ToString(dtSanctionView.Rows[0]["LevelName"]);
                    Status = Convert.ToString(dtSanctionView.Rows[0]["Status"]);
                    strTypeOfLeave = Convert.ToString(dtSanctionView.Rows[0]["Type"]);
                    YearSettingID = Convert.ToInt16(dtSanctionView.Rows[0]["YearSettings_Id"]);
                }
                if (Convert.ToString(Session["UserGroupName"]) != "SuperAdmin")
                {
                    Status = GetUpdatedStatusBasedOnSanctioning(Employee_Id);
                }
                else
                    Status = GetUpdatedStatus();
                if (btnSaveLeaveSanction.CommandName == "Rejected" || lnkbtn.CommandName == "Rejected")
                {
                    Status = "Rejected";
                }
                NumberOfDays = Convert.ToDouble(dtSanctionView.Rows[0]["NumberOfDays"]);
                LeaveTypeId = Convert.ToInt32(dtSanctionView.Rows[0]["LeaveType_id"]);
                bool boolChkLeave = true;
                int intLeaveCount = 0;
                #region SavingLeaveApplication
                try
                {
                    if (strTypeOfLeave == "Leave")
                    {
                        if (Convert.ToString(ViewState["StatusBorrow"]) == "False")
                            if (Status == "Approved")
                                objLeaveApplicationEventData.UpdateYearClosureByLeaveSanction(NumberOfDays, LeaveTypeId, Employee_Id, "A", Convert.ToInt32(Session["EmpAutoId"]), YearSettingID);
                        if (Convert.ToString(ViewState["StatusBorrow"]) == "True")
                        {
                            DataSet dsRemainingNoOfleaves = new DataSet();
                            double dblCurrLeave = 0.0;
                            if (Convert.ToString(ViewState["StatusOnLoad"]) != Status)
                            {
                                if (Status == "Approved")
                                {
                                    intLeaveCount = objLeaveApplicationEventData.CheckLeaveExistsBeforeBorrow(Leave_FromDate, Leave_ToDate, LeaveTypeId, Employee_Id);
                                    if (intLeaveCount > 0)
                                    {
                                        boolChkLeave = false;
                                        base.Message(rm.GetString("Msg_Alreadycurrentyearleaveapplicationsareavailabletoapprovereject", ci));
                                        return;
                                    }
                                    else
                                    {
                                        dsRemainingNoOfleaves = objLeaveApplicationEventData.GetRemainingNumberOfLeaves(Employee_Id, LeaveTypeId);
                                        dsRemainingNoOfleaves.Tables[0].TableName = "Details";
                                        if (dsRemainingNoOfleaves.Tables.Count > 0)
                                        {
                                            if (dsRemainingNoOfleaves.Tables[0].Rows.Count > 0)
                                            {
                                                dblCurrLeave = Convert.ToDouble(dsRemainingNoOfleaves.Tables["Details"].Rows[0]["RemainingNoOfLeaves"]);
                                            }
                                        }
                                        if (dblCurrLeave > 0)
                                        {
                                            boolChkLeave = false;
                                            base.Message(rm.GetString("Msg_Currentyearquotaavailableforthisleavetype", ci));
                                            return;
                                        }
                                        objLeaveApplicationEventData.UpdateYearClosureByLeaveSanction(NumberOfDays, LeaveTypeId, Employee_Id, "AB", Convert.ToInt32(Session["EmpAutoId"]), YearSettingID);
                                    }
                                }
                            }
                        }
                    }
                    if (boolChkLeave == true)
                        objLeaveApplicationEventData.UpdateLeaveApplicationSanction(LeaveApplication_Id, Status, Convert.ToInt32(Session["EmpAutoId"]), "Ok", Convert.ToInt32(Session["EmpAutoId"]));
                    objLeaveApplicationEventData.UpdateLeaveApplicationConversation(LeaveApplication_Id, Status, Convert.ToInt32(Session["EmpAutoId"]), "Ok", Convert.ToInt32(Session["EmpAutoId"]));
                    objLeaveApplicationEventData.UpdateProcessedDataFlag(Employee_Id, Leave_FromDate, Leave_ToDate, 0);
                    ds_EmailIdOfSanctionAuthority = objPermissionEventData.SelectMailIdOfSanctionAuthority(Employee_Id);
                    if (ds_EmailIdOfSanctionAuthority.Tables[0].Rows.Count > 0)
                        if (ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"] != DBNull.Value)
                            if (Convert.ToString(ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"]) != string.Empty)
                                strEmailIdSanctionAuthority = Convert.ToString(ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"]);
                    dsEmailIdOfReportingTo = objPermissionEventData.SelectMailIdOfReportingTo(Employee_Id);
                    if (dsEmailIdOfReportingTo.Tables[0].Rows.Count > 0)
                        if (dsEmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"] != DBNull.Value)
                            if (Convert.ToString(dsEmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"]) != string.Empty)
                                strEmailIdReportingTo = Convert.ToString(dsEmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"]);
                    if (Convert.ToInt32(ConfigurationManager.AppSettings.Get("isRequiredEmail")) == 1)
                    {
                        SendMailToApplicant(Convert.ToInt32(Session["LevelId"]), LeaveApplication_Id, empEmailId, strEmailIdReportingTo, strEmailIdSanctionAuthority, EmployeeName, Status, "Ok", strLeaveApplicationDate, strNoOfDays, Convert.ToString(ViewState["LeaveType"]), Convert.ToString(dtSanctionView.Rows[0]["Leave_FromDate"]), Convert.ToString(dtSanctionView.Rows[0]["Leave_ToDate"]), Convert.ToString(dtSanctionView.Rows[0]["Leave_SessionFrom"]), Convert.ToString(dtSanctionView.Rows[0]["Leave_SessionTo"]), strReason);
                    }
                    #region SMSNotification
                    try
                    {
                        int smsIsRequired = 0;
                        //To check SMS Template is available in page table or not. if no then it will skip the SMS Triggering portion.
                        //244 is template page id
                        smsIsRequired = objClassCommon.CheckPageExistsInLicense(244);
                        if (smsIsRequired > 0)
                        {
                            DataSet dsGateway = new DataSet();
                            DataSet dsStatus = new DataSet();
                            bool isSmsEnabledForEmployee = false;
                            string destinationKey = string.Empty;
                            string MessageKey = string.Empty;
                            string ServiceUrl = string.Empty;
                            string mobileNo = string.Empty;
                            string strTemplateName = string.Empty;
                            string EmployeecodeId = string.Empty;
                            bool isApplyAndReceiverSame = false;
                            string empName = string.Empty;
                            if (Status == "Pending")
                                strTemplateName = "Leave Application - Apply";
                            else if (Status == "Forwarded")
                                strTemplateName = "Leave Application - Forward";
                            else if (Status == "Approved")
                                strTemplateName = "Leave Application - Approved";
                            else if (Status == "Approved")
                                strTemplateName = "Leave Application - Approved";
                            else if (Status == "Rejected")
                                strTemplateName = "Leave Application - Rejected";
                            dsStatus = objsms.GetTemplateStauts(strTemplateName);
                            if (dsStatus.Tables.Count > 0)
                            {
                                if (dsStatus.Tables[0].Rows.Count > 0 && Convert.ToBoolean(dsStatus.Tables[0].Rows[0]["Status"]) != false)
                                {
                                    dsGateway = objsms.SelectGatewayDetails();
                                    if (dsGateway.Tables.Count > 0)
                                    {
                                        if (dsGateway.Tables[0].Rows.Count > 0)
                                        {
                                            if (dsGateway.Tables[0].Rows[0]["ServiceUrl"] != null)
                                                ServiceUrl = Convert.ToString(dsGateway.Tables[0].Rows[0]["ServiceUrl"]);
                                            if (dsGateway.Tables[0].Rows[0]["DestinationKey"] != null)
                                                destinationKey = Convert.ToString(dsGateway.Tables[0].Rows[0]["DestinationKey"]);
                                            if (dsGateway.Tables[0].Rows[0]["MessageKey"] != null)
                                                MessageKey = Convert.ToString(dsGateway.Tables[0].Rows[0]["MessageKey"]);
                                            if (dsStatus.Tables[0].Rows[0]["ToEmployee"] != null)
                                                isSmsEnabledForEmployee = Convert.ToBoolean(dsStatus.Tables[0].Rows[0]["ToEmployee"]);
                                            if (isSmsEnabledForEmployee)
                                            {
                                                if (dtSanctionView.Rows.Count > 0)
                                                {
                                                    if (dtSanctionView.Rows[0]["Mobile_Number"] != null)
                                                        mobileNo = Convert.ToString(dtSanctionView.Rows[0]["Mobile_Number"]);
                                                    if (dtSanctionView.Rows[0]["Employee_code_id"] != null)
                                                        EmployeecodeId = Convert.ToString(dtSanctionView.Rows[0]["Employee_code_id"]);
                                                    if (dtSanctionView.Rows[0]["Employee_FirstName"] != null)
                                                        empName = Convert.ToString(dtSanctionView.Rows[0]["Employee_FirstName"]);
                                                }
                                            }
                                            DataSet dsReceivers = new DataSet();
                                            string[] strleaveType = Convert.ToString(ViewState["LeaveType"]).Split('/');
                                            dsReceivers = objsms.GetReceiversDetails(strTemplateName, EmployeecodeId, EmployeeName, Leave_FromDate + " To " + Leave_FromDate, strleaveType[0], Convert.ToString(strNoOfDays));
                                            if (dsReceivers.Tables.Count > 0)
                                            {
                                                if (dsReceivers.Tables[1].Rows.Count > 0)
                                                {
                                                    foreach (DataRow dr in dsReceivers.Tables[1].Rows)
                                                    {
                                                        if (Convert.ToString(dr["Mobile_Number"]) != "")
                                                        {
                                                            blnCheckSMS = objsms.SendSMSNotifications
                                                            (
                                                                ServiceUrl,
                                                                destinationKey,
                                                                MessageKey,
                                                                Convert.ToString(dr["Receivers"]),
                                                                Convert.ToString(dsReceivers.Tables[0].Rows[0]["Message"]),
                                                                Convert.ToString(dr["Mobile_Number"]),
                                                                EmployeecodeId,
                                                                strTemplateName,
                                                                Convert.ToString(dr["SwipeCardNo"])
                                                            );
                                                            if (isSmsEnabledForEmployee)
                                                            {
                                                                if (Convert.ToString(dr["SwipeCardNo"]) == EmployeecodeId)
                                                                {
                                                                    isApplyAndReceiverSame = true;
                                                                }
                                                            }
                                                        }
                                                        else
                                                        {
                                                            objsms.InsertLogDetails(strTemplateName, Convert.ToString(dr["SwipeCardNo"]), EmployeecodeId, false, Convert.ToString(dsReceivers.Tables[0].Rows[0]["Message"]), "Mobile Number is not configured in employee master");
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    objsms.InsertLogDetails(strTemplateName, "", EmployeecodeId, false, Convert.ToString(dsReceivers.Tables[0].Rows[0]["Message"]), "Receivers are not having the configured usergroup");
                                                }
                                                if (isSmsEnabledForEmployee)
                                                {
                                                    if (mobileNo != string.Empty && isApplyAndReceiverSame != true)
                                                    {
                                                        blnCheckSMS = objsms.SendSMSNotifications
                                                                        (
                                                                            ServiceUrl,
                                                                            destinationKey,
                                                                            MessageKey,
                                                                            empName,
                                                                            Convert.ToString(dsReceivers.Tables[0].Rows[0]["Message"]),
                                                                            Convert.ToString(mobileNo),
                                                                            EmployeecodeId,
                                                                             strTemplateName,
                                                                        Convert.ToString(EmployeecodeId)
                                                                        );
                                                    }
                                                    else if (mobileNo == string.Empty && isApplyAndReceiverSame != true)
                                                    {
                                                        objsms.InsertLogDetails(strTemplateName, Convert.ToString(EmployeecodeId), EmployeecodeId, false, Convert.ToString(dsReceivers.Tables[0].Rows[0]["Message"]), "Mobile Number is not configured in employee master");
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                    #endregion
                    if (checkEmail == true && blnCheckSMS == true)
                    {
                        MessageWithReplace(rm.GetString("Alert_LeaveSanctionApplicationSaved", ci), "TA_UI_Transaction_Sanctions.aspx?Type=Leave");
                        Session["SanctionSelected"] = "1";
                    }
                    else
                    {
                        if (NotSendedEmployeeCodeId == "")
                            NotSendedEmployeeCodeId = Convert.ToString(Employee_Code_Id);
                        else
                        {
                            string[] ExistEmployeeCode = NotSendedEmployeeCodeId.Split(',');
                            if (ExistEmployeeCode.Length > 0)
                            {
                                int pos = Array.IndexOf(ExistEmployeeCode, Employee_Code_Id);
                                if (pos <= -1)
                                    NotSendedEmployeeCodeId = NotSendedEmployeeCodeId + ',' + Convert.ToString(Employee_Code_Id);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Message(ex.ToString());
                }
                #endregion
            }
            if (NotSendedEmployeeCodeId != null)
            {
                Session["SanctionSelected"] = "1";
                hdnSelectRow.Value = "";
                if (checkEmail == false && blnCheckSMS == true)
                    MessageWithReplace(rm.GetString("Alert_LeaveSanctionApplicationSavedEmailnotsent_Bulk", ci) + NotSendedEmployeeCodeId, "TA_UI_Transaction_Sanctions.aspx?Type=Leave");
                else if (checkEmail == true && blnCheckSMS == false)
                    MessageWithReplace(rm.GetString("Alert_LeaveApplicationSavedbutSMSisnotTriggered1_Bulk", ci) + NotSendedEmployeeCodeId, "TA_UI_Transaction_Sanctions.aspx?Type=Leave");
                else
                    MessageWithReplace(rm.GetString("Alert_LeaveApplicationSavedbutEmailSMSisNotSend_Bulk", ci) + NotSendedEmployeeCodeId, "TA_UI_Transaction_Sanctions.aspx?Type=Leave");
            }
            else
                Message(rm.GetString("PleaseSelectAnyOneLeaveApplication", ci));
            //UserSelected_SanctionType();
            if (ddlStatus.SelectedItem.Value == "Pending" || ddlStatus.SelectedItem.Value == "Forwarded")
            {
                bindLeaveSanctionDetailsForBulkApproval("Load");
            }
            else
            {
                bindLeaveSanctionDetails("Load");
            }
            if (test.Length == gdLeaveSanctionViewBulk.VisibleRowCount)
                Session["LeaveChecked"] = null;
            else
                Session["LeaveChecked"] = null;
            isClear = false;
            #endregion
        }
        else
            Message(rm.GetString("PleaseSelectAnyOneLeaveApplication", ci));
    }
    private string GetUpdatedStatusBasedOnSanctioning(int appid)
    {
        string newStatus = "Forwarded";
        if (Convert.ToString(Session["ReportsBasedOn"]) == "True")
        {
            ds_ReportingToSanctionAuthorityList = objLeaveApplicationEventData.GetReportingToSanctionAuthorityforID(appid);
            if (ds_ReportingToSanctionAuthorityList.Tables.Count > 0)
            {
                if (ds_ReportingToSanctionAuthorityList.Tables[0].Rows.Count > 0)
                {
                    if (Convert.ToString(Session["EmpAutoId"]) == Convert.ToString(ds_ReportingToSanctionAuthorityList.Tables[0].Rows[0]["Reporting_To"]) && Convert.ToString(Session["EmpAutoId"]) == Convert.ToString(ds_ReportingToSanctionAuthorityList.Tables[0].Rows[0]["Leave_Sanc_Authority"]))
                    {
                        newStatus = "Approved";
                    }
                    else if (Convert.ToString(Session["EmpAutoId"]) == Convert.ToString(ds_ReportingToSanctionAuthorityList.Tables[0].Rows[0]["Reporting_To"]))
                    {
                        newStatus = "Forwarded";
                    }
                    else if (Convert.ToString(Session["EmpAutoId"]) == Convert.ToString(ds_ReportingToSanctionAuthorityList.Tables[0].Rows[0]["Leave_Sanc_Authority"]))
                    {
                        newStatus = "Approved";
                    }
                }
            }
        }
        else
        {
            newStatus = GetUpdatedStatus();
        }
        return newStatus;
    }
    private string GetUpdatedStatus()
    {
        switch (Status)
        {
            case "Forwarded":
                Status = "Approved";
                break;
            case "Pending":
                Status = "Forwarded";
                break;
        }
        return Status;
    }
    protected void btnSavePermission_Click(object sender, EventArgs e)
    {
        if (hdnSelectRow.Value != string.Empty)
        {
            DataTable dsCheckedItem;
            dsCheckedItem = (DataTable)Session["PermissionChecked"];
            chkBoxIDs = objLeave.commaStringToArray(hdnSelectRow.Value);
            for (int i = 0; i < chkBoxIDs.Length; i++)
            {
                Permission_Id = Convert.ToInt32(chkBoxIDs[i]);
                dtSanctionView = objPermissionEventData.GetPermissionByPermissionId(Permission_Id);
                if (dtSanctionView.Rows.Count > 0)
                {
                    if (dtSanctionView.Rows[0]["EmailId"] != DBNull.Value)
                        empEmailId = dtSanctionView.Rows[0]["EmailId"].ToString();
                    if (dtSanctionView.Rows[0]["Employee_Id"] != DBNull.Value)
                        Employee_Id = Convert.ToInt32(dtSanctionView.Rows[0]["Employee_Id"]);
                    if (dtSanctionView.Rows[0]["Employee_Code_Id"] != DBNull.Value)
                        Employee_Code_Id = dtSanctionView.Rows[0]["Employee_Code_Id"].ToString();
                    if (dtSanctionView.Rows[0]["Employee_FirstName"] != DBNull.Value)
                        EmployeeName = dtSanctionView.Rows[0]["Employee_FirstName"].ToString();
                    if (dtSanctionView.Rows[0]["name"] != DBNull.Value)
                        strlevelName = dtSanctionView.Rows[0]["name"].ToString();
                    strReason = dtSanctionView.Rows[0]["Permission_Reason"].ToString();
                    gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
                    gstrTimeFormat = Session["MTimeFormat"].ToString();
                    string strFromDateTime = string.Empty;
                    string strToDateTime = string.Empty;
                    string[] PerTime = dtSanctionView.Rows[0]["Permission_FromTime"].ToString().Split(" ".ToCharArray());
                    string timePart1 = PerTime[0].ToString() + " " + PerTime[1].ToString();
                    lblPermissionFromTime = (Convert.ToDateTime(PerTime[0])).ToString(Session["MDateFormat"].ToString()) + " " + DateTime.Parse(timePart1).ToString(Session["MTimeFormat"].ToString());
                    string[] PerTime1 = dtSanctionView.Rows[0]["Permission_ToTime"].ToString().Split(" ".ToCharArray());
                    string timePart2 = PerTime1[0].ToString() + " " + PerTime1[1].ToString();
                    lblPermissionToTime = (Convert.ToDateTime(PerTime1[0])).ToString(Session["MDateFormat"].ToString()) + " " + DateTime.Parse(timePart2).ToString(Session["MTimeFormat"].ToString());
                    lblPermissionDate = (Convert.ToDateTime(dtSanctionView.Rows[0]["Permission_Date"])).ToString(Session["MDateFormat"].ToString());
                    Status = dtSanctionView.Rows[0]["Permission_Status"].ToString();
                    strFromDateTime = objClassCommon.DateTimeConvertion((gstrDateFormat + " " + gstrTimeFormat), lblPermissionFromTime, "B");
                    strToDateTime = objClassCommon.DateTimeConvertion((gstrDateFormat + " " + gstrTimeFormat), lblPermissionToTime, "B");
                    string dNumberOfHoursApplied = string.Empty;
                    dNumberOfHoursApplied = CalculateNumberOfHoursApplied(strFromDateTime, strToDateTime);
                    if (Convert.ToString(Session["UserGroupName"]) != "SuperAdmin")
                    {
                        ds_ReportingToSanctionAuthorityList = objLeaveApplicationEventData.SelectReportingToSanctionAuthorityForPermission(Permission_Id);
                        if (ds_ReportingToSanctionAuthorityList.Tables.Count > 0)
                        {
                            if (ds_ReportingToSanctionAuthorityList.Tables[0].Rows.Count > 0)
                            {
                                if (Convert.ToString(Session["EmpAutoId"]) == Convert.ToString(ds_ReportingToSanctionAuthorityList.Tables[0].Rows[0]["Reporting_To"]) && Convert.ToString(Session["EmpAutoId"]) == Convert.ToString(ds_ReportingToSanctionAuthorityList.Tables[0].Rows[0]["Leave_Sanc_Authority"]))
                                {
                                    Status = "Approved";
                                }
                                else if (Convert.ToString(Session["EmpAutoId"]) == Convert.ToString(ds_ReportingToSanctionAuthorityList.Tables[0].Rows[0]["Reporting_To"]))
                                {
                                    Status = "Forwarded";
                                }
                                else if (Convert.ToString(Session["EmpAutoId"]) == Convert.ToString(ds_ReportingToSanctionAuthorityList.Tables[0].Rows[0]["Leave_Sanc_Authority"]))
                                {
                                    Status = "Approved";
                                }
                                else
                                {
                                    Status = GetUpdatedStatus();
                                }
                            }
                            else
                            {
                                Status = GetUpdatedStatus();
                            }
                        }
                        else
                        {
                            Status = GetUpdatedStatus();
                        }
                    }
                    else
                    {
                        Status = GetUpdatedStatus();
                    }
                    Remarks = "";
                    try
                    {
                        objPermissionEventData.UpdatePermissionApplicationConversation(Permission_Id, Status, Convert.ToInt32(Session["EmpAutoId"]), "OK", Convert.ToInt32(Session["EmpAutoId"]));
                        objPermissionEventData.UpdatePermissionSanction(Permission_Id, Status, Remarks, Convert.ToInt32(Session["EmpAutoId"]));
                        cls_Common objclscommon = new cls_Common();
                        string strPermissionDate = objclscommon.DateConvertion(gstrDateFormat, lblPermissionDate);
                        objLeaveApplicationEventData.UpdateProcessedDataFlag(Employee_Id, strPermissionDate, strPermissionDate, 0);
                        ds_EmailIdOfSanctionAuthority = objPermissionEventData.SelectMailIdOfSanctionAuthority(Employee_Id);
                        if (ds_EmailIdOfSanctionAuthority.Tables[0].Rows.Count > 0)
                        {
                            if (ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"] != DBNull.Value)
                            {
                                if (ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"].ToString() != "")
                                {
                                    strEmailIdSanctionAuthority = ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"].ToString();
                                }
                            }
                        }
                        dsEmailIdOfReportingTo = objPermissionEventData.SelectMailIdOfReportingTo(Employee_Id);
                        string strEmailIdReportingTo = string.Empty;
                        if (dsEmailIdOfReportingTo.Tables[0].Rows.Count > 0)
                        {
                            if (dsEmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"] != DBNull.Value)
                                if (dsEmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"].ToString() != string.Empty)
                                    strEmailIdReportingTo = dsEmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"].ToString();
                        }
                        if (Convert.ToInt32(ConfigurationManager.AppSettings.Get("isRequiredEmail")) == 1)
                        {
                            SendMailToApplicantPermission(empEmailId, strEmailIdReportingTo, strEmailIdSanctionAuthority, Status, strReason, Employee_Code_Id, dNumberOfHoursApplied, strlevelName, EmployeeName);
                        }
                        #region SMSNotification
                        try
                        {
                            int smsIsRequired = 0;
                            //To check SMS Template is available in page table or not. if no then it will skip the SMS Triggering portion.
                            //244 is template page id
                            smsIsRequired = objClassCommon.CheckPageExistsInLicense(244);
                            if (smsIsRequired > 0)
                            {
                                DataSet dsGateway = new DataSet();
                                DataSet dsStatus = new DataSet();
                                bool isSmsEnabled = false;
                                string destinationKey = string.Empty;
                                string MessageKey = string.Empty;
                                string ServiceUrl = string.Empty;
                                string mobileNo = string.Empty;
                                string strTemplateName = string.Empty;
                                bool isApplyAndReceiverSame = false;
                                if (Status == "Pending")
                                    strTemplateName = "Permission Application - Apply";
                                else if (Status == "Forwarded")
                                    strTemplateName = "Permission Application - Forward";
                                else if (Status == "Approved")
                                    strTemplateName = "Permission Application - Approved";
                                else if (Status == "Rejected")
                                    strTemplateName = "Permission Application - Rejected";
                                dsStatus = objsms.GetTemplateStauts(strTemplateName);
                                if (dsStatus.Tables.Count > 0)
                                {
                                    if (dsStatus.Tables[0].Rows.Count > 0 && Convert.ToBoolean(dsStatus.Tables[0].Rows[0]["Status"]) != false)
                                    {
                                        dsGateway = objsms.SelectGatewayDetails();
                                        if (dsGateway.Tables.Count > 0)
                                        {
                                            if (dsGateway.Tables[0].Rows.Count > 0)
                                            {
                                                if (dsGateway.Tables[0].Rows[0]["ServiceUrl"] != null)
                                                    ServiceUrl = Convert.ToString(dsGateway.Tables[0].Rows[0]["ServiceUrl"]);
                                                if (dsGateway.Tables[0].Rows[0]["DestinationKey"] != null)
                                                    destinationKey = Convert.ToString(dsGateway.Tables[0].Rows[0]["DestinationKey"]);
                                                if (dsGateway.Tables[0].Rows[0]["MessageKey"] != null)
                                                    MessageKey = Convert.ToString(dsGateway.Tables[0].Rows[0]["MessageKey"]);
                                                if (dsStatus.Tables[0].Rows[0]["ToEmployee"] != null)
                                                    isSmsEnabled = Convert.ToBoolean(dsStatus.Tables[0].Rows[0]["ToEmployee"]);
                                                if (dtSanctionView.Rows.Count > 0)
                                                {
                                                    if (dtSanctionView.Rows[0]["Mobile_Number"] != null)
                                                        mobileNo = Convert.ToString(dtSanctionView.Rows[0]["Mobile_Number"]);
                                                    if (dtSanctionView.Rows[0]["Employee_FirstName"] != null)
                                                        EmployeeName = Convert.ToString(dtSanctionView.Rows[0]["Employee_FirstName"]);
                                                }
                                                DataSet dsReceivers = new DataSet();
                                                dsReceivers = objsms.GetReceiversDetails(strTemplateName, Employee_Code_Id, EmployeeName, lblPermissionFromTime + " To " + lblPermissionToTime, "", Convert.ToString(dNumberOfHoursApplied));
                                                if (dsReceivers.Tables.Count > 0)
                                                {
                                                    if (dsReceivers.Tables[1].Rows.Count > 0)
                                                    {
                                                        foreach (DataRow dr in dsReceivers.Tables[1].Rows)
                                                        {
                                                            if (Convert.ToString(dr["Mobile_Number"]) != "")
                                                            {
                                                                blnCheckSMS = objsms.SendSMSNotifications
                                                                (
                                                                    ServiceUrl,
                                                                    destinationKey,
                                                                    MessageKey,
                                                                    Convert.ToString(dr["Receivers"]),
                                                                    Convert.ToString(dsReceivers.Tables[0].Rows[0]["Message"]),
                                                                    Convert.ToString(dr["Mobile_Number"]),
                                                                    Employee_Code_Id,
                                                                    strTemplateName,
                                                                    Convert.ToString(dr["SwipeCardNo"])
                                                                );
                                                                if (isSmsEnabled)
                                                                {
                                                                    if (Convert.ToString(dr["SwipeCardNo"]) == Employee_Code_Id)
                                                                    {
                                                                        isApplyAndReceiverSame = true;
                                                                    }
                                                                }
                                                            }
                                                            else
                                                            {
                                                                objsms.InsertLogDetails(strTemplateName, Convert.ToString(dr["SwipeCardNo"]), Employee_Code_Id, false, Convert.ToString(dsReceivers.Tables[0].Rows[0]["Message"]), "Mobile Number is not configured in employee master");
                                                            }
                                                        }
                                                    }
                                                    else
                                                    {
                                                        objsms.InsertLogDetails(strTemplateName, "", Employee_Code_Id, false, Convert.ToString(dsReceivers.Tables[0].Rows[0]["Message"]), "Receivers are not having the configured usergroup");
                                                    }
                                                    if (isSmsEnabled)
                                                    {
                                                        if (mobileNo != string.Empty && isApplyAndReceiverSame != true)
                                                        {
                                                            blnCheckSMS = objsms.SendSMSNotifications
                                                                            (
                                                                                ServiceUrl,
                                                                                destinationKey,
                                                                                MessageKey,
                                                                                EmployeeName,
                                                                                Convert.ToString(dsReceivers.Tables[0].Rows[0]["Message"]),
                                                                                Convert.ToString(mobileNo),
                                                                                Employee_Code_Id,
                                                                                 strTemplateName,
                                                                            Convert.ToString(Employee_Code_Id)
                                                                            );
                                                        }
                                                        else if (mobileNo == string.Empty && isApplyAndReceiverSame != true)
                                                        {
                                                            objsms.InsertLogDetails(strTemplateName, Convert.ToString(Employee_Code_Id), Employee_Code_Id, false, Convert.ToString(dsReceivers.Tables[0].Rows[0]["Message"]), "Mobile Number is not configured in employee master");
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                        #endregion
                        if (checkEmail == true)
                        {
                            hdnSelectRow.Value = "";
                            MessageWithReplace(rm.GetString("Alert_PermissionApplicationsavedSanction", ci), "TA_UI_Transaction_Sanctions.aspx?Type=Permission");
                            Session["SanctionSelected"] = "2";
                        }
                        else
                        {
                            if (NotSendedEmployeeCodeId == "")
                            {
                                NotSendedEmployeeCodeId = Employee_Code_Id;
                            }
                            else
                            {
                                string[] ExistEmployeeCode = NotSendedEmployeeCodeId.Split(',');
                                if (ExistEmployeeCode.Length > 0)
                                {
                                    int pos = Array.IndexOf(ExistEmployeeCode, Employee_Code_Id);
                                    if (pos <= -1)
                                    {
                                        NotSendedEmployeeCodeId = NotSendedEmployeeCodeId + ',' + Employee_Code_Id;
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Message(ex.ToString());
                    }
                }
            }
            //UserSelected_SanctionType();
            BindPermissionSanction("isload");
            if (NotSendedEmployeeCodeId != null)
            {
                hdnSelectRow.Value = "";
                MessageWithReplace(rm.GetString("Alert_PermissionApplicationsavedEmailnotsent_BulkSanction", ci) + NotSendedEmployeeCodeId, "TA_UI_Transaction_Sanctions.aspx?Type=Permission");
                Session["SanctionSelected"] = "2";
            }
        }
        else
        {
            Message(rm.GetString("Alert_SelectAnyOneApplication", ci));
        }
    }
    protected void btnSaveOndutySanction_Click(object sender, EventArgs e)
    {
        string strReason = "";
        cls_Common objClassCommon = new cls_Common();
        DataTable dtSanctionView = new DataTable();
        DataSet dsSanctionView = new DataSet();
        #region OnDutyUpdation
        if (hdnSelectRow.Value != "")
        {
            string strPreStatus = "";
            chkBoxIDs = objLeave.commaStringToArray(hdnSelectRow.Value);
            for (int i = 0; i < chkBoxIDs.Length; i++)
            {
                gintManualTimeEntryId = Convert.ToInt32(chkBoxIDs[i]);
                ViewState["Permission_Id"] = gintManualTimeEntryId;
                dsSanctionView = objManualEntryEventData.SelectODEntryById(gintManualTimeEntryId);
                dtSanctionView = dsSanctionView.Tables[0];
                if (dtSanctionView.Rows.Count > 0)
                {
                    int EmployeeID = Convert.ToInt16(dsSanctionView.Tables[0].Rows[0]["Employee_Id"]);
                    Status = strPreStatus = Convert.ToString(dsSanctionView.Tables[0].Rows[0]["Onduty_Status"]);
                    strReason = Convert.ToString(dsSanctionView.Tables[0].Rows[0]["Onduty_Reason"]);
                    int LevelID = 0;
                    string EmployeeCodeID = string.Empty;
                    Session["dtSanctionView"] = dtSanctionView;
                    if (Convert.ToString(Session["UserGroupName"]) != "SuperAdmin")
                    {
                        ds_ReportingToSanctionAuthorityList = objLeaveApplicationEventData.GetReportingToSanctionAuthorityforID(EmployeeID);
                        if (ds_ReportingToSanctionAuthorityList.Tables.Count > 0)
                        {
                            if (ds_ReportingToSanctionAuthorityList.Tables[0].Rows.Count > 0)
                            {
                                if (Convert.ToString(Session["EmpAutoId"]) == Convert.ToString(ds_ReportingToSanctionAuthorityList.Tables[0].Rows[0]["Reporting_To"]) && Convert.ToString(Session["EmpAutoId"]) == Convert.ToString(ds_ReportingToSanctionAuthorityList.Tables[0].Rows[0]["Leave_Sanc_Authority"]))
                                {
                                    Status = "Approved";
                                }
                                else if (Convert.ToString(Session["EmpAutoId"]) == Convert.ToString(ds_ReportingToSanctionAuthorityList.Tables[0].Rows[0]["Reporting_To"]))
                                {
                                    Status = "Forwarded";
                                }
                                else if (Convert.ToString(Session["EmpAutoId"]) == Convert.ToString(ds_ReportingToSanctionAuthorityList.Tables[0].Rows[0]["Leave_Sanc_Authority"]))
                                {
                                    Status = "Approved";
                                }
                                else
                                {
                                    Status = GetUpdatedStatus();
                                }
                            }
                            else
                            {
                                Status = GetUpdatedStatus();
                            }
                        }
                        else
                        {
                            Status = GetUpdatedStatus();
                        }
                    }
                    else
                    {
                        Status = GetUpdatedStatus();
                    }
                    EmployeeCodeID = dtSanctionView.Rows[0]["Employee_Code_Id"].ToString();
                    DataSet dsEmployeeDetails = new DataSet();
                    dsEmployeeDetails = objLeaveApplicationEventData.GetEmployeeDetails(Convert.ToInt32(EmployeeID));
                    if (dsEmployeeDetails.Tables[0].Rows.Count > 0)
                    {
                        strEmpFirstName = Convert.ToString(dsEmployeeDetails.Tables[0].Rows[0]["Employee_FirstName"]);
                        strEmpLastName = Convert.ToString(dsEmployeeDetails.Tables[0].Rows[0]["Employee_LastName"]);
                        strEmployeeCodeId = Convert.ToString(dsEmployeeDetails.Tables[0].Rows[0]["Employee_Code_Id"]);
                        strEmployeeName = strEmpFirstName + " " + strEmpLastName;
                        strlevelName = Convert.ToString(dsEmployeeDetails.Tables[0].Rows[0]["levelName"]);
                        strEmployeeEmailId = Convert.ToString(dsEmployeeDetails.Tables[0].Rows[0]["EmailID"]);
                        strEmailIdSanctioningAuthority = Convert.ToString(dsEmployeeDetails.Tables[0].Rows[0]["ApprovalAuthorityEmailID"]);
                        strEmailIdReportingTo = Convert.ToString(dsEmployeeDetails.Tables[0].Rows[0]["ReportingToEmailID"]);
                        LevelID = Convert.ToInt32(dsEmployeeDetails.Tables[0].Rows[0]["LevelID"]);
                    }
                    UpdatedManualTimeEntryStatus(Status);
                    if (strPreStatus != Status)
                    {
                        if (Convert.ToInt32(ConfigurationManager.AppSettings.Get("isRequiredEmail")) == 1)
                        {
                            SendMailOnduty(Convert.ToInt32(gintManualTimeEntryId), LevelID, strEmployeeEmailId, strEmailIdReportingTo, strEmailIdSanctioningAuthority, dtSanctionView.Rows[0]["Onduty_FromDate"].ToString(), dtSanctionView.Rows[0]["Onduty_FromTime"].ToString(), dtSanctionView.Rows[0]["Onduty_ToDate"].ToString(), dtSanctionView.Rows[0]["Onduty_ToTime"].ToString(), dtSanctionView.Rows[0]["Onduty_EntryDate"].ToString(), strEmployeeName, strEmployeeCodeId, strReason, strlevelName, Status);
                        }
                        #region SMSNotification
                        try
                        {
                            int smsIsRequired = 0;
                            //To check SMS Template is available in page table or not. if no then it will skip the SMS Triggering portion.
                            //244 is template page id
                            smsIsRequired = objClassCommon.CheckPageExistsInLicense(244);
                            if (smsIsRequired > 0)
                            {
                                DataSet dsGateway = new DataSet();
                                DataSet dsStatus = new DataSet();
                                bool isSmsEnabled = false;
                                string destinationKey = string.Empty;
                                string MessageKey = string.Empty;
                                string ServiceUrl = string.Empty;
                                string mobileNo = string.Empty;
                                string strTemplateName = string.Empty;
                                bool isApplyAndReceiverSame = false;
                                if (Status == "Pending")
                                    strTemplateName = "OnDuty - Apply";
                                else if (Status == "Forwarded")
                                    strTemplateName = "OnDuty - Forward";
                                else if (Status == "Approved")
                                    strTemplateName = "OnDuty - Approved";
                                else if (Status == "Rejected")
                                    strTemplateName = "OnDuty - Rejected";
                                dsStatus = objsms.GetTemplateStauts(strTemplateName);
                                if (dsStatus.Tables.Count > 0)
                                {
                                    if (dsStatus.Tables[0].Rows.Count > 0 && Convert.ToBoolean(dsStatus.Tables[0].Rows[0]["Status"]) != false)
                                    {
                                        dsGateway = objsms.SelectGatewayDetails();
                                        if (dsGateway.Tables.Count > 0)
                                        {
                                            if (dsGateway.Tables[0].Rows.Count > 0)
                                            {
                                                if (dsGateway.Tables[0].Rows[0]["ServiceUrl"] != null)
                                                    ServiceUrl = Convert.ToString(dsGateway.Tables[0].Rows[0]["ServiceUrl"]);
                                                if (dsGateway.Tables[0].Rows[0]["DestinationKey"] != null)
                                                    destinationKey = Convert.ToString(dsGateway.Tables[0].Rows[0]["DestinationKey"]);
                                                if (dsGateway.Tables[0].Rows[0]["MessageKey"] != null)
                                                    MessageKey = Convert.ToString(dsGateway.Tables[0].Rows[0]["MessageKey"]);
                                                if (dsStatus.Tables[0].Rows[0]["ToEmployee"] != null)
                                                    isSmsEnabled = Convert.ToBoolean(dsStatus.Tables[0].Rows[0]["ToEmployee"]);
                                                if (isSmsEnabled)
                                                {
                                                    if (dtSanctionView.Rows.Count > 0)
                                                        if (dtSanctionView.Rows[0]["Mobile_Number"] != null)
                                                            mobileNo = Convert.ToString(dtSanctionView.Rows[0]["Mobile_Number"]);
                                                }
                                                if (dtSanctionView.Rows.Count > 0)
                                                {
                                                    if (dtSanctionView.Rows[0]["Employee_Name"] != null)
                                                        EmployeeName = Convert.ToString(dtSanctionView.Rows[0]["Employee_Name"]);
                                                }
                                                DataSet dsReceivers = new DataSet();
                                                dsReceivers = objsms.GetReceiversDetails(strTemplateName, strEmployeeCodeId, strEmpFirstName, Convert.ToString(dtSanctionView.Rows[0]["Onduty_FromDate"]) + " " + Convert.ToDateTime(dtSanctionView.Rows[0]["Onduty_FromTime"]).ToString(TimeFormatMail) + " To " + Convert.ToString(dtSanctionView.Rows[0]["Onduty_ToDate"]) + " " + Convert.ToDateTime(dtSanctionView.Rows[0]["Onduty_FromTime"].ToString()).ToString(TimeFormatMail), "", Convert.ToString(""));
                                                if (dsReceivers.Tables.Count > 0)
                                                {
                                                    if (dsReceivers.Tables[1].Rows.Count > 0)
                                                    {
                                                        foreach (DataRow dr in dsReceivers.Tables[1].Rows)
                                                        {
                                                            if (Convert.ToString(dr["Mobile_Number"]) != "")
                                                            {
                                                                blnCheckSMS = objsms.SendSMSNotifications
                                                                (
                                                                    ServiceUrl,
                                                                    destinationKey,
                                                                    MessageKey,
                                                                    Convert.ToString(dr["Receivers"]),
                                                                    Convert.ToString(dsReceivers.Tables[0].Rows[0]["Message"]),
                                                                    Convert.ToString(dr["Mobile_Number"]),
                                                                    strEmployeeCodeId,
                                                                    strTemplateName,
                                                                    Convert.ToString(dr["SwipeCardNo"])
                                                                );
                                                                if (isSmsEnabled)
                                                                {
                                                                    if (Convert.ToString(dr["SwipeCardNo"]) == Employee_Code_Id)
                                                                    {
                                                                        isApplyAndReceiverSame = true;
                                                                    }
                                                                }
                                                            }
                                                            else
                                                            {
                                                                objsms.InsertLogDetails(strTemplateName, Convert.ToString(dr["SwipeCardNo"]), Employee_Code_Id, false, Convert.ToString(dsReceivers.Tables[0].Rows[0]["Message"]), "Mobile Number is not configured in employee master");
                                                            }
                                                        }
                                                    }
                                                    else
                                                    {
                                                        objsms.InsertLogDetails(strTemplateName, "", Employee_Code_Id, false, Convert.ToString(dsReceivers.Tables[0].Rows[0]["Message"]), "Receivers are not having the configured usergroup");
                                                    }
                                                }
                                                if (isSmsEnabled)
                                                {
                                                    if (mobileNo != string.Empty && isApplyAndReceiverSame != true)
                                                    {
                                                        blnCheckSMS = objsms.SendSMSNotifications
                                                                    (
                                                                        ServiceUrl,
                                                                        destinationKey,
                                                                        MessageKey,
                                                                        EmployeeName,
                                                                        Convert.ToString(dsReceivers.Tables[0].Rows[0]["Message"]),
                                                                        Convert.ToString(mobileNo),
                                                                        strEmployeeCodeId,
                                                                         strTemplateName,
                                                                    Convert.ToString(strEmployeeCodeId)
                                                                    );
                                                    }
                                                    else if (mobileNo == string.Empty && isApplyAndReceiverSame != true)
                                                    {
                                                        objsms.InsertLogDetails(strTemplateName, Convert.ToString(Employee_Code_Id), Employee_Code_Id, false, Convert.ToString(dsReceivers.Tables[0].Rows[0]["Message"]), "Mobile Number is not configured in employee master");
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Message(ex.ToString());
                        }
                        #endregion
                    }
                }
            }
            //UserSelected_SanctionType();
            if (InsertCount > 0)
            {
                Session["dtSanctionView"] = null;
                BindOndutySanctionDetails("");
                MessageWithReplace(rm.GetString("Alert_OndutyApplicationsavedSanction", ci), "TA_UI_Transaction_Sanctions.aspx?Type=Onduty");
                Session["SanctionSelected"] = "3";
            }
        }
        else
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Alert_Selectanyentrytochangestatus", ci) + "');", true);
            return;
        }
        #endregion
    }
    #endregion
    #region GridviewEvents
    #region LeaveSanction
    protected void gdLeaveSanctionView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label lbl = (Label)e.Row.Cells[1].FindControl("Label1");
            string date1 = (Convert.ToDateTime(lbl.Text)).ToString(Session["MDateFormat"].ToString());
            lbl.Text = date1;
            e.Row.Cells[1].Controls.Add(lbl);
            Label lbldur = (Label)e.Row.Cells[1].FindControl("Label3");
            string[] duration = lbldur.Text.Split(" - ".ToCharArray());
            string datedur = (Convert.ToDateTime(duration[0])).ToString(Session["MDateFormat"].ToString());
            string datedur1 = (Convert.ToDateTime(duration[3])).ToString(Session["MDateFormat"].ToString());
            lbldur.Text = datedur + " - " + datedur1;
            e.Row.Cells[2].Controls.Add(lbldur);
            Label lblStatus = (Label)e.Row.Cells[1].FindControl("Label1");
            commonRowDataBound(lblStatus);
        }
    }
    private void commonRowDataBound(Label lblStatus)
    {
        if (lblStatus != null)
        {
            switch (lblStatus.Text)
            {
                case "Approved":
                    lblStatus.Text = rm.GetString("btn_Approved", ci);
                    break;
                case "Forwarded":
                    lblStatus.Text = rm.GetString("btn_Forwarded", ci);
                    break;
                case "Pending":
                    lblStatus.Text = rm.GetString("btn_Pending", ci);
                    break;
                case "Rejected":
                    lblStatus.Text = rm.GetString("btn_Reject", ci);
                    break;
            }
        }
    }
    protected void gdLeaveSanctionView_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gdLeaveSanctionView.PageIndex = e.NewPageIndex;
        gdLeaveSanctionView.DataSource = Session["DataLeaveSanction"];
        gdLeaveSanctionView.DataBind();
    }
    public void SortGrid(string SortColumn, string SortOrder)
    {
        DataTable dtSrch = new DataTable();
        DataView dvSearch = new DataView();
        dtSrch = (DataTable)Session["DataLeaveSanction"];
        dvSearch.Table = dtSrch;
        dvSearch.Sort = SortColumn + " " + SortOrder;
        gdLeaveSanctionView.DataSource = dvSearch;
        gdLeaveSanctionView.DataBind();
    }
    protected void gdLeaveSanctionView_Sorting(object sender, GridViewSortEventArgs e)
    {
        ViewState["SortExpression"] = e.SortExpression;
        if (Convert.ToString(Session["SortOrderLeaveSanction"]) == string.Empty)
            Session["SortOrderLeaveSanction"] = "Asc";
        else if (Convert.ToString(Session["SortOrderLeaveSanction"]) == "Asc")
            Session["SortOrderLeaveSanction"] = "Desc";
        else
            Session["SortOrderLeaveSanction"] = "Asc";
        SortGrid(e.SortExpression, Convert.ToString(Session["SortOrderLeaveSanction"]));
    }
    protected void gdLeaveSanctionView_PageIndexChanged(object sender, EventArgs e)
    {
        try
        {
            // To display the sorted records in the new page if the Vendor has Sorted the Gridview by clicking any header
            if ((ViewState["SortExpression"]) != null)
            {
                string SortColumn = Convert.ToString(ViewState["SortExpression"]);
                string SortOrder = Convert.ToString(Session["SortOrderLeaveSanction"]);
                SortGrid(SortColumn, SortOrder);
            }
        }
        catch (Exception ex)
        {
            Message(ex.ToString());
        }
    }
    protected void gdLeaveSanctionView_HtmlRowCreated(object sender, DevExpress.Web.ASPxGridViewTableRowEventArgs e)
    {
        if (e.RowType == DevExpress.Web.GridViewRowType.Data)
        {
            source_Language = Convert.ToString(Session["Session_ActiveLanguage"]);
            rm = new ResourceManager(source_Language, System.Reflection.Assembly.Load("App_GlobalResources"));
            ci = Thread.CurrentThread.CurrentCulture;
            LoadStrings(ci);
            Label lbl = (Label)gdLeaveSanctionView.FindRowCellTemplateControl(e.VisibleIndex, null, "Label1");
            string date1 = (Convert.ToDateTime(lbl.Text)).ToString(Session["MDateFormat"].ToString());
            lbl.Text = date1;
            e.Row.Cells[1].Controls.Add(lbl);
            Label lbldur = (Label)gdLeaveSanctionView.FindRowCellTemplateControl(e.VisibleIndex, null, "Label3");
            string[] duration = lbldur.Text.Split(" - ".ToCharArray());
            string datedur = (Convert.ToDateTime(duration[0])).ToString(Session["MDateFormat"].ToString());
            string datedur1 = (Convert.ToDateTime(duration[3])).ToString(Session["MDateFormat"].ToString());
            lbldur.Text = datedur + " - " + datedur1;
            e.Row.Cells[2].Controls.Add(lbldur);
            Label lblStatus = (Label)e.Row.Cells[1].FindControl("Label1");
            commonRowDataBound(lblStatus);
        }
    }
    #endregion
    #region LeaveSanctionBulk
    public void SortGridBulk(string SortColumn, string SortOrder)
    {
        DataTable dtSrch = new DataTable();
        DataView dvSearch = new DataView();
        dtSrch = (DataTable)Session["DataLeaveSanctionBulk"];
        dvSearch.Table = dtSrch;
        dvSearch.Sort = SortColumn + " " + SortOrder;
        gdLeaveSanctionViewBulk.DataSource = dvSearch;
        gdLeaveSanctionViewBulk.DataBind();
    }
    protected void gdLeaveSanctionViewBulk_PageIndexChanged(object sender, EventArgs e)
    {
        try
        {
            if ((ViewState["SortExpression"]) != null)
            {
                string SortColumn = Convert.ToString(ViewState["SortExpression"]);
                string SortOrder = Convert.ToString(Session["SortOrderLeaveSanction"]);
                SortGridBulk(SortColumn, SortOrder);
            }
        }
        catch (Exception ex)
        {
            Message(ex.ToString());
        }
    }
    protected void gdLeaveSanctionViewBulk_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label lbl = (Label)e.Row.Cells[1].FindControl("Label1");
            string date1 = (Convert.ToDateTime(lbl.Text)).ToString(Convert.ToString(Session["MDateFormat"]));
            lbl.Text = date1;
            Label lbldur = (Label)e.Row.Cells[1].FindControl("Label3");
            string[] duration = lbldur.Text.Split(" - ".ToCharArray());
            string datedur = (Convert.ToDateTime(duration[0])).ToString(Convert.ToString(Session["MDateFormat"]));
            string datedur1 = (Convert.ToDateTime(duration[3])).ToString(Convert.ToString(Session["MDateFormat"]));
            lbldur.Text = datedur + " - " + datedur1;
            Label lblStatus = (Label)e.Row.Cells[1].FindControl("Label2");
            commonRowDataBound(lblStatus);
        }
    }
    protected void gdLeaveSanctionViewBulk_Sorting(object sender, GridViewSortEventArgs e)
    {
        ViewState["SortExpression"] = e.SortExpression;
        if (Convert.ToString(Session["SortOrderLeaveSanction"]) == string.Empty)
            Session["SortOrderLeaveSanction"] = "Asc";
        else if (Convert.ToString(Session["SortOrderLeaveSanction"]) == "Asc")
            Session["SortOrderLeaveSanction"] = "Desc";
        else
            Session["SortOrderLeaveSanction"] = "Asc";
        SortGridBulk(e.SortExpression, Convert.ToString(Session["SortOrderLeaveSanction"]));
    }
    protected void gdLeaveSanctionViewBulk_HtmlRowCreated(object sender, DevExpress.Web.ASPxGridViewTableRowEventArgs e)
    {
        if (e.RowType == DevExpress.Web.GridViewRowType.Data)
        {
            source_Language = Convert.ToString(Session["Session_ActiveLanguage"]);
            rm = new ResourceManager(source_Language, System.Reflection.Assembly.Load("App_GlobalResources"));
            ci = Thread.CurrentThread.CurrentCulture;
            Label lbl = (Label)gdLeaveSanctionViewBulk.FindRowCellTemplateControl(e.VisibleIndex, null, "Label1");
            string date1 = (Convert.ToDateTime(lbl.Text)).ToString(Convert.ToString(Session["MDateFormat"]));
            e.Row.Cells[3].Text = date1;
            string lbldur = Convert.ToString(e.GetValue("Duration"));
            string[] duration = lbldur.Split(" - ".ToCharArray());
            string datedur = (Convert.ToDateTime(duration[0])).ToString(Convert.ToString(Session["MDateFormat"]));
            string datedur1 = (Convert.ToDateTime(duration[3])).ToString(Convert.ToString(Session["MDateFormat"]));
            lbldur = datedur + " - " + datedur1;
            e.Row.Cells[4].Text = lbldur;
            Label lblStatus = (Label)gdLeaveSanctionViewBulk.FindRowCellTemplateControl(e.VisibleIndex, null, "Label2");
            commonRowDataBound(lblStatus);
        }
    }
    #endregion
    #region PermissionSanction
    public void SortGridPermission(string SortColumn, string SortOrder)
    {
        DataTable dtSrch = new DataTable();
        DataView dvSearch = new DataView();
        dtSrch = (DataTable)Session["DataPermissionSanction"];
        dvSearch.Table = dtSrch;
        dvSearch.Sort = SortColumn + " " + SortOrder;
        gdPermissionSanctionView.DataSource = dvSearch;
        gdPermissionSanctionView.DataBind();
    }
    protected void gdPermissionSanctionView_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gdPermissionSanctionView.PageIndex = e.NewPageIndex;
        gdPermissionSanctionView.DataSource = Session["DataPermissionSanction"];
        gdPermissionSanctionView.DataBind();
    }
    protected void gdPermissionSanctionView_Sorting(object sender, GridViewSortEventArgs e)
    {
        ViewState["SortExpression"] = e.SortExpression;
        if (Convert.ToString(Session["SortOrder"]) == string.Empty)
            Session["SortOrder"] = "Asc";
        else if (Convert.ToString(Session["SortOrder"]) == "Asc")
            Session["SortOrder"] = "Desc";
        else
            Session["SortOrder"] = "Asc";
        SortGridPermission(e.SortExpression, Convert.ToString(Session["SortOrder"]));
    }
    protected void gdPermissionSanctionView_HtmlRowCreated(object sender, DevExpress.Web.ASPxGridViewTableRowEventArgs e)
    {
        if (e.RowType == GridViewRowType.Data)
        {
            source_Language = Convert.ToString(Session["Session_ActiveLanguage"]);
            rm = new ResourceManager(source_Language, System.Reflection.Assembly.Load("App_GlobalResources"));
            ci = Thread.CurrentThread.CurrentCulture;
            string lbl = Convert.ToString(e.GetValue("Permission_AppliedDate"));
            string Lbl_FromTime = Convert.ToString(e.GetValue("Permission_FromTime"));
            string Lbl_EndTime = Convert.ToString(e.GetValue("Permission_ToTime"));
            string TEndTime;
            TEndTime = DateTime.Parse(Lbl_EndTime).ToShortTimeString();
            string TFromTime;
            TFromTime = DateTime.Parse(Lbl_FromTime).ToString(Session["MDateFormat"].ToString()) + "&nbsp;" + DateTime.Parse(Lbl_FromTime).ToString(Session["MTimeFormat"].ToString());
            e.Row.Cells[3].Text = TFromTime + " To " + TEndTime;
            Label lblStatus = (Label)gdPermissionSanctionView.FindRowCellTemplateControl(e.VisibleIndex, null, "lblPermissionStatus");
            commonRowDataBound(lblStatus);
        }
    }
    protected void gdPermissionSanctionView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label lbl_Duration = (Label)e.Row.FindControl("lbl_Duration");
            Label lbl = (Label)e.Row.FindControl("PermissionAppliedDate");
            Label Lbl_FromTime = (Label)e.Row.FindControl("Lbl_FromTime");
            Label Lbl_EndTime = (Label)e.Row.FindControl("Lbl_EndTime");
            string TEndTime;
            TEndTime = DateTime.Parse(Lbl_EndTime.Text).ToShortTimeString();
            string TFromTime;
            TFromTime = DateTime.Parse(Lbl_FromTime.Text).ToString(Session["MDateFormat"].ToString()) + "&nbsp;&nbsp;&nbsp;" + DateTime.Parse(Lbl_FromTime.Text).ToString(Session["MTimeFormat"].ToString());
            lbl_Duration.Text = TFromTime + " To " + TEndTime;
            string date1 = (Convert.ToDateTime(lbl.Text)).ToString(Session["MDateFormat"].ToString());
            lbl.Text = date1;
            e.Row.Cells[2].Controls.Add(lbl);
            Label lblStatus = (Label)e.Row.FindControl("lblPermissionStatus");
            commonRowDataBound(lblStatus);
        }
    }
    protected void gdPermissionSanctionView_PageIndexChanged(object sender, EventArgs e)
    {
        try
        {
            if ((ViewState["SortExpression"]) != null)
            {
                string SortColumn = Convert.ToString(ViewState["SortExpression"]);
                string SortOrder = Convert.ToString(Session["SortOrder"]);
                SortGridPermission(SortColumn, SortOrder);
            }
        }
        catch (Exception ex)
        {
            Message(ex.ToString());
        }
    }
    #endregion
    #region PermissionSanctionBulk
    public void SortGridPermissionBulk(string SortColumn, string SortOrder)
    {
        DataTable dtSrch = new DataTable();
        DataView dvSearch = new DataView();
        dtSrch = (DataTable)ViewState["DataPermissionSanctionBulk"];
        dvSearch.Table = dtSrch;
        dvSearch.Sort = SortColumn + " " + SortOrder;
        gdPermissionSanctionViewBulk.DataSource = dvSearch;
        gdPermissionSanctionViewBulk.DataBind();
    }
    protected void gdPermissionSanctionViewBulk_PageIndexChanged(object sender, EventArgs e)
    {
        try
        {
            if ((ViewState["SortExpression"]) != null)
            {
                string SortColumn = Convert.ToString(ViewState["SortExpression"]);
                string SortOrder = Convert.ToString(Session["SortOrder"]);
                SortGridPermissionBulk(SortColumn, SortOrder);
            }
        }
        catch (Exception ex)
        {
            Message(ex.ToString());
        }
    }
    protected void gdPermissionSanctionViewBulk_Sorting(object sender, GridViewSortEventArgs e)
    {
        ViewState["SortExpression"] = e.SortExpression;
        if (Convert.ToString(Session["SortOrder"]) == string.Empty)
            Session["SortOrder"] = "Asc";
        else if (Convert.ToString(Session["SortOrder"]) == "Asc")
            Session["SortOrder"] = "Desc";
        else
            Session["SortOrder"] = "Asc";
        SortGridPermissionBulk(e.SortExpression, Convert.ToString(Session["SortOrder"]));
    }
    protected void gdPermissionSanctionViewBulk_HtmlRowCreated(object sender, DevExpress.Web.ASPxGridViewTableRowEventArgs e)
    {
        if (e.RowType == GridViewRowType.Data)
        {
            source_Language = Convert.ToString(Session["Session_ActiveLanguage"]);
            rm = new ResourceManager(source_Language, System.Reflection.Assembly.Load("App_GlobalResources"));
            ci = Thread.CurrentThread.CurrentCulture;
            string Label1 = (string)e.GetValue("Permission_AppliedDate");
            string Lbl_FromTime = e.GetValue("Permission_FromTime").ToString();
            string Lbl_EndTime = e.GetValue("Permission_ToTime").ToString();
            string TEndTime;
            TEndTime = DateTime.Parse(Lbl_EndTime).ToString(Session["MTimeFormat"].ToString());
            string TFromTime;
            TFromTime = DateTime.Parse(Lbl_FromTime).ToString(Session["MDateFormat"].ToString()) + "&nbsp;" + DateTime.Parse(Lbl_FromTime).ToString(Session["MTimeFormat"].ToString());
            e.Row.Cells[4].Text = TFromTime + " To " + TEndTime;
            Label lblStatus = (Label)gdPermissionSanctionViewBulk.FindRowCellTemplateControl(e.VisibleIndex, null, "lblPermissionStatus");
            commonRowDataBound(lblStatus);
        }
    }
    #endregion
    #endregion
    private string GetEmptyText()
    {
        return "No Record Found";
    }
    protected void checkall_CheckedChanged(object sender, EventArgs e)
    {
    }
    protected void deletethis_CheckedChanged(object sender, EventArgs e)
    {
    }
    protected void grvTimesheetEntry_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            TextBox txtApproved = (TextBox)e.Row.FindControl("txtApproved");
            if (txtApproved != null)
            {
                txtApproved.Attributes.Add("onmouseover", "javascript:return DynamicDatePickerForTime('','" + txtApproved.ClientID + "')");
            }
            CheckBox chkSelect = (CheckBox)e.Row.FindControl("chkSelect");
            //Merge Rows
            //We're only interested in Rows that contain data
            //get a reference to the data used to databound the row
            DataRowView drv = ((DataRowView)e.Row.DataItem);
            if (previousCat == drv["RecordID"].ToString())
            {
                if (grvTimesheetEntry.Rows.Count >= 1)
                {
                    if (firstRow < grvTimesheetEntry.Rows.Count)
                    {
                        //If it's the same category as the previous one
                        //Increment the rowspan
                        if (grvTimesheetEntry.Rows[firstRow].Cells[0].RowSpan == 0)
                        {
                            grvTimesheetEntry.Rows[firstRow].Cells[0].RowSpan = 2;
                            grvTimesheetEntry.Rows[firstRow].Cells[1].RowSpan = 2;
                            grvTimesheetEntry.Rows[firstRow].Cells[2].RowSpan = 2;
                            grvTimesheetEntry.Rows[firstRow].Cells[3].RowSpan = 2;
                            grvTimesheetEntry.Rows[firstRow].Cells[4].RowSpan = 2;
                        }
                        else
                        {
                            grvTimesheetEntry.Rows[firstRow].Cells[0].RowSpan += 1;
                            grvTimesheetEntry.Rows[firstRow].Cells[1].RowSpan += 1;
                            grvTimesheetEntry.Rows[firstRow].Cells[2].RowSpan += 1;
                            grvTimesheetEntry.Rows[firstRow].Cells[3].RowSpan += 1;
                            grvTimesheetEntry.Rows[firstRow].Cells[4].RowSpan += 1;
                        }
                        //Remove the cell
                        //e.Row.Cells.RemoveAt(0);       
                        e.Row.Cells[0].Visible = false;
                        e.Row.Cells[1].Visible = false;
                        e.Row.Cells[2].Visible = false;
                        e.Row.Cells[3].Visible = false;
                        e.Row.Cells[4].Visible = false;
                    }
                    else //It's a new category
                    {
                        //Set the vertical alignment to top
                        e.Row.VerticalAlign = VerticalAlign.Middle;
                        //Maintain the category in memory
                        previousCat = "";
                        firstRow = -1;
                    }
                }
            }
            else //It's a new category
            {
                //Set the vertical alignment to top
                e.Row.VerticalAlign = VerticalAlign.Middle;
                //Maintain the category in memory
                previousCat = drv["RecordID"].ToString();
                firstRow = e.Row.RowIndex;
            }
            if (Convert.ToString(Session["UserGroupName"]) != "SuperAdmin")
            {
                if (Convert.ToString(ddlStatus.SelectedItem.Text) == "Approved")
                {
                    if (chkSelect != null)
                    {
                        chkSelect.Enabled = false;
                    }
                }
            }
        }
    }
    protected void lnkbtnTimesheetApproval_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            bool isChecked = false;
            LinkButton btn = (LinkButton)sender;
            Int64 prevId = 0;
            double taskTimeSpan = 0;
            try
            {
                #region ValidateSelectedRecords
                foreach (GridViewRow row in grvTimesheetEntry.Rows)
                {
                    CheckBox chkSelect = (CheckBox)row.Cells[0].FindControl("chkSelect");
                    Label lblRecordID = (Label)row.Cells[0].FindControl("lblRecordID");
                    if (chkSelect != null)
                    {
                        if (chkSelect.Checked)
                        {
                            taskTimeSpan = 0;
                            isChecked = true;
                            Label lblTaskDetailID = (Label)row.Cells[0].FindControl("lblTaskDetailID");
                            TextBox txtApproved = (TextBox)row.Cells[0].FindControl("txtApproved");
                            Label lblempAutoID = (Label)row.Cells[0].FindControl("lblempAutoID");
                            Label lblSpentHours = (Label)row.Cells[0].FindControl("lblSpentHours");
                            if (lblTaskDetailID != null && txtApproved != null && lblempAutoID != null && lblSpentHours != null)
                            {
                                if (Convert.ToString(txtApproved.Text) == "")
                                {
                                    Message("Please fill the approved hours before saving");
                                    return;
                                }
                                else if (Convert.ToDateTime(txtApproved.Text) > Convert.ToDateTime(lblSpentHours.Text))
                                {
                                    Message("Approved hours should not be greater than spent hours");
                                    return;
                                }
                                if (lblRecordID != null)
                                {
                                    prevId = Convert.ToInt64(lblRecordID.Text);
                                }
                                taskTimeSpan = Convert.ToDateTime(txtApproved.Text).TimeOfDay.TotalMinutes;
                            }
                        }
                        else
                        {
                            if (lblRecordID != null)
                            {
                                if (Convert.ToInt64(lblRecordID.Text) == prevId)
                                {
                                    isChecked = true;
                                    Label lblTaskDetailID = (Label)row.Cells[0].FindControl("lblTaskDetailID");
                                    TextBox txtApproved = (TextBox)row.Cells[0].FindControl("txtApproved");
                                    Label lblempAutoID = (Label)row.Cells[0].FindControl("lblempAutoID");
                                    Label lblSpentHours = (Label)row.Cells[0].FindControl("lblSpentHours");
                                    if (lblTaskDetailID != null && txtApproved != null && lblempAutoID != null && lblSpentHours != null)
                                    {
                                        if (Convert.ToString(txtApproved.Text) == "")
                                        {
                                            Message("Please fill the approved hours before saving");
                                            return;
                                        }
                                        else if (Convert.ToDateTime(txtApproved.Text) > Convert.ToDateTime(lblSpentHours.Text))
                                        {
                                            Message("Approved hours should not be greater than spent hours");
                                            return;
                                        }
                                        taskTimeSpan = taskTimeSpan + Convert.ToDateTime(txtApproved.Text).TimeOfDay.TotalMinutes;
                                        if (taskTimeSpan > 24 * 60)
                                        {
                                            Message("Approved hours should not be more than 24 hours");
                                            return;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                if (!isChecked)
                {
                    Message(rm.GetString("PleaseSelectAnyOneTimesheet", ci));
                    return;
                }
                #endregion
            }
            catch (Exception ex)
            {
                Message("Validation Error: " + ex.ToString());
            }
            #region SaveRecords
            try
            {
                prevId = 0;
                int rowCount = grvTimesheetEntry.Rows.Count;
                int startValue = 1;
                foreach (GridViewRow row in grvTimesheetEntry.Rows)
                {
                    CheckBox chkSelect = (CheckBox)row.Cells[0].FindControl("chkSelect");
                    Label lblRecordID = (Label)row.Cells[0].FindControl("lblRecordID");
                    if (lblRecordID != null)
                    {
                        if (prevId != 0 && Convert.ToInt64(lblRecordID.Text) != prevId)
                        {
                            if (btn.CommandName == "Approved")
                            {
                                if (ViewState["VS_ShiftDate"] != null && ViewState["VS_taskTimeSpan"] != null && ViewState["VS_empAutoID"] != null)
                                {
                                    Status = "Approved";
                                    // update Timing into Manual Time Entry. Flag =4 used for timesheet.
                                    objtimeSheet.UpdateClockTimingsBasedOnApprovedHours(Convert.ToString(ViewState["VS_ShiftDate"]), Convert.ToInt16(ViewState["VS_taskTimeSpan"]), Status, Convert.ToString(Session["EmpAutoID"]), Convert.ToString(ViewState["VS_empAutoID"]));
                                    ViewState["VS_ShiftDate"] = null;
                                    ViewState["VS_taskTimeSpan"] = null;
                                    ViewState["VS_empAutoID"] = null;
                                    prevId = 0;
                                    isChecked = true;
                                    taskTimeSpan = 0;
                                }
                            }
                        }
                    }
                    if (chkSelect != null)
                    {
                        Label lblTaskDetailID = (Label)row.Cells[0].FindControl("lblTaskDetailID");
                        TextBox txtApproved = (TextBox)row.Cells[0].FindControl("txtApproved");
                        Label lblempAutoID = (Label)row.Cells[0].FindControl("lblempAutoID");
                        Label lblSpentHours = (Label)row.Cells[0].FindControl("lblSpentHours");
                        Label lblShiftDate = (Label)row.Cells[0].FindControl("lblShiftDate");
                        if (chkSelect.Checked)
                        {
                            isChecked = true;
                            if (lblRecordID != null)
                            {
                                prevId = Convert.ToInt64(lblRecordID.Text);
                            }
                            if (lblTaskDetailID != null && txtApproved != null && lblempAutoID != null && lblSpentHours != null)
                            {
                                int TaskDetailID = int.Parse(lblTaskDetailID.Text);
                                Status = (ddlStatus.SelectedItem.Text);
                                if (Convert.ToString(Session["UserGroupName"]) != "SuperAdmin")
                                {
                                    Status = GetUpdatedStatusBasedOnSanctioning(Convert.ToInt32(lblempAutoID.Text));
                                }
                                else
                                {
                                    Status = GetUpdatedStatus();
                                }
                                if (btn.CommandName == "Rejected")
                                {
                                    Status = "Rejected";
                                }
                                taskTimeSpan = Convert.ToDateTime(txtApproved.Text).TimeOfDay.TotalMinutes;
                                objtimeSheet.UpdateApprovalStatus(TaskDetailID, Convert.ToString(txtApproved.Text), Status, Convert.ToInt64(Session["EmpAutoID"]), Convert.ToInt64(lblempAutoID.Text), "");
                                if (lblShiftDate != null)
                                {
                                    ViewState["VS_ShiftDate"] = Convert.ToString(lblShiftDate.Text);
                                }
                                if (lblempAutoID != null)
                                {
                                    ViewState["VS_empAutoID"] = Convert.ToString(lblempAutoID.Text);
                                }
                            }
                        }
                        else
                        {
                            if (lblRecordID != null)
                            {
                                if (Convert.ToInt64(lblRecordID.Text) == prevId)
                                {
                                    isChecked = true;
                                    if (lblTaskDetailID != null && txtApproved != null && lblempAutoID != null && lblSpentHours != null)
                                    {
                                        int TaskDetailID = int.Parse(lblTaskDetailID.Text);
                                        Status = (ddlStatus.SelectedItem.Text);
                                        if (Convert.ToString(Session["UserGroupName"]) != "SuperAdmin")
                                        {
                                            Status = GetUpdatedStatusBasedOnSanctioning(Convert.ToInt32(lblempAutoID.Text));
                                        }
                                        else
                                        {
                                            Status = GetUpdatedStatus();
                                        }
                                        if (btn.CommandName == "Rejected")
                                        {
                                            Status = "Rejected";
                                        }
                                        taskTimeSpan = taskTimeSpan + Convert.ToDateTime(txtApproved.Text).TimeOfDay.TotalMinutes;
                                        objtimeSheet.UpdateApprovalStatus(TaskDetailID, Convert.ToString(txtApproved.Text), Status, Convert.ToInt64(Session["EmpAutoID"]), Convert.ToInt64(lblempAutoID.Text), "");
                                    }
                                }
                            }
                        }
                        ViewState["VS_taskTimeSpan"] = taskTimeSpan;
                    }
                    if (prevId != 0 && Convert.ToInt64(lblRecordID.Text) == prevId && startValue == rowCount)
                    {
                        if (btn.CommandName == "Approved")
                        {
                            if (ViewState["VS_ShiftDate"] != null && ViewState["VS_taskTimeSpan"] != null && ViewState["VS_empAutoID"] != null)
                            {
                                Status = "Approved";
                                // update Timing into Manual Time Entry. Flag =4 used for timesheet.
                                objtimeSheet.UpdateClockTimingsBasedOnApprovedHours(Convert.ToString(ViewState["VS_ShiftDate"]), Convert.ToInt16(ViewState["VS_taskTimeSpan"]), Status, Convert.ToString(Session["EmpAutoID"]), Convert.ToString(ViewState["VS_empAutoID"]));
                                ViewState["VS_ShiftDate"] = null;
                                ViewState["VS_taskTimeSpan"] = null;
                                ViewState["VS_empAutoID"] = null;
                                prevId = 0;
                                isChecked = true;
                                taskTimeSpan = 0;
                            }
                        }
                    }
                    startValue += 1;
                }
                BindTimeSheetEntry("Unload");
                Message("Timesheet entry application was saved Successfully");
                return;
            }
            catch (Exception ex)
            {
                Message("To Save records: " + ex.ToString());
            }
            #endregion
        }
    }
    protected void grvTimesheetEntry_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grvTimesheetEntry.PageIndex = e.NewPageIndex;
        BindTimeSheetEntry("Unload");
    }
    protected void btnTemplate_Click(object sender, EventArgs e)
    {
        try
        {
            //Response.Clear();
            //Response.AddHeader("Content-Type", "application/Excel");
            //Response.ContentType = "application/octet-stream";
            //Response.AddHeader("Content-Disposition", "attachment;filename=TimecheckMasterData.csv");
            //Response.BinaryWrite(data);
            //Response.End();
            string file = string.Empty;
            file = "1086_AllPresent";
            Response.Clear();
            Response.ContentType = "application/octet-stream";
            Response.AddHeader("content-disposition", "attachment;filename=" + Path.GetFileName(file));
            Response.WriteFile(Server.MapPath(file));
            // This would be the ideal spot to collect some download statistics and / or tracking  
            // also, you could implement other requests, such as delete the file after download  
            Response.End();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    protected void btnDownload_Click(object sender, EventArgs e)
    {
        ImageButton btn = sender as ImageButton;
        int intEmpid = Convert.ToInt32(btn.CommandArgument);
        Random rnd = new Random();
        Download_MedicalCertificate(intEmpid);
    }
    private bool Download_MedicalCertificate(int LeaveApplication_ID)
    {
        string GetType = "SelectMedicalCertificate";
        bool fileflage = false;
        int LeaveApplication_Id = LeaveApplication_ID;
        DataSet dsFileDetails = objLeaveApplicationEventData.EditLeaveApplication_FileUpload(LeaveApplication_Id, GetType);
        if (dsFileDetails.Tables[0].Rows.Count > 0)
        {
            string GetPath = dsFileDetails.Tables[0].Rows[0]["FilePath"].ToString();
            string filename = Path.GetFileName(GetPath);
            string FilePath = Server.MapPath("~/Transactions/LeaveApplicationUploadFiles/" + filename);
            FileInfo fileInfo = new FileInfo(FilePath);
            if (fileInfo.Exists)
            {
                Response.Clear();
                Response.AddHeader("Content-Disposition", "attachment; filename=" + fileInfo.Name);
                Response.AddHeader("Content-Length", fileInfo.Length.ToString());
                Response.ContentType = "application/octet-stream";
                Response.Flush();
                Response.TransmitFile(fileInfo.FullName);
                Response.End();
                fileflage = true;
            }
            else
            {
                ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('" + rm.GetString("Alert_MedicalCertificateNotAvailable", ci) + "');", true);
                fileflage = false;
            }
        }
        return fileflage;
    }
}