using System;
using System.Configuration;
using System.Data;
using System.Globalization;
using System.IO;
using System.Net;
using System.Resources;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.Configuration;
using System.Web.UI;
using OLServices;
using Cryptographys;
using System.Net.Mail;
using System.Net.NetworkInformation;
using System.DirectoryServices;
using System.Collections;

public partial class Index : System.Web.UI.Page
{
    #region Variable
    ResourceManager rm;
    cls_Common objCommon = new cls_Common();
    MultiLingualEventData objMultiLingualEventData = new MultiLingualEventData();
    LeaveApplicationEventData objLeaveApplicationEventData = new LeaveApplicationEventData();
    ShiftSettingsEventData objShiftSettingsEventData = new ShiftSettingsEventData();
    EmployeeEventData ObjEmployeeEventData = new EmployeeEventData();
    ShiftExchange objshift = new ShiftExchange();
    DataSet ds_MultiLingual = new DataSet();
    DataSet dsEmployeeLingual = new DataSet();
    ResetPwd obj_ResetPwd = new ResetPwd();
    EmployeeEventData objEmployeeEventData = new EmployeeEventData();
    Rpt_Common rptcommon = new Rpt_Common();
    int count, IsActive;
    string strUsername, strPassword, UserName;
    DataSet ds_UserName;
    DataSet dsLoginLock = new DataSet();
    byte[] inputBytes, hashBytes;
    DataSet user;
    string strSetAlert;
    string strScript = "";
    string userId, ipAddress, session_Id, res, db_sessionId;
    bool status = true;
    DateTime inTime;
    string source_Language;
    CultureInfo ci;
    bool flag = false;
    int payrollConfig = 0;
    #endregion

    #region LicenseProcess Variables
    Licensing objLicense = new Licensing();
    OL_Services Objservices = new OL_Services();
    // variable for modules
    int master, transaction, report, organizationSetting, systemSetting;
    // variable for protection table license information
    int dongleId, customerId, softwareId, packageId, noOfConcurrentUser;
    string packageVersion;
    DateTime expiryDate, dateOfIssue;
    //LDAP
    string currentSystemloginuserName = string.Empty;
    string isDomainLoginRequired = "0";
    bool isDomainLoginRequiredflag = false;
    #endregion

    #region PageLoad
    protected void Page_Load(object sender, EventArgs e)
    {
        //strCusConfigID = Encryption.Decrypt("JDvRzgOH8YAFq/xDsAFkag==", "");
        //string strDecryptedString = Cryptographys.Cryptography.Decrypt("gDyjbM1uuaetYB1KZOOEyLXZxT3UchoFCwh/FN3+aC6zTRd2Z/szDokVXJ7+L2LhGB1siqMtBqNUhM20m6OF4OgzRBzPT3dMXYkWAAYbz9yKXFmgp7PTWDxqs0zIm+wT" providerName = ", "TimecheckPhaseI");
        //loadco();
        if (Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["DefaultLanguage"]) != "")
        {
            source_Language = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["DefaultLanguage"]);
        }
        rm = new ResourceManager(source_Language, System.Reflection.Assembly.Load("App_GlobalResources"));

        hdnEmpID.Value = Convert.ToString(Request.QueryString["EmpID"]);
        HdnReportName.Value= Convert.ToString(Request.QueryString["ReportName"]);
        HdnFrom.Value = Convert.ToString(Request.QueryString["From"]);
        HdnTo.Value = Convert.ToString(Request.QueryString["To"]);
        HdnReportNo.Value = Convert.ToString(Request.QueryString["Rep"]);
        HdnAuthorityNo.Value = Convert.ToString(Request.QueryString["Authority"]);

        Session["hdnEmpID"] = hdnEmpID.Value;
        Session["HdnReportName"] = HdnReportName.Value;
        Session["HdnFrom"] = HdnFrom.Value;
        Session["HdnTo"] = HdnTo.Value;
        Session["HdnReport"] = HdnReportNo.Value;
        Session["HdnAuthority"] = HdnAuthorityNo.Value;


        ci = Thread.CurrentThread.CurrentCulture;
        if (!Page.IsPostBack)
        {
            LoadStrings(ci);
            if (Request.Browser.MajorVersion < 7)
            {
                Message("The Site is browser compactable with IE 8 and above versions");
            }
            
            if (Request.QueryString["T"] != null)
             {
                    MessageWithRedirect("Your session was expired.", "Index.aspx");
                    return;
             }            
            
            if (Request.Cookies["TCUName"] != null)
                txt_UserName.Text = Convert.ToString(Request.Cookies["TCUName"].Value);
            if (Request.Cookies["TCPwd"] != null)
                txt_Password.Attributes.Add("value", Request.Cookies["TCPwd"].Value);
            if (Request.Cookies["TCUName"] != null && Request.Cookies["TCPwd"] != null)
                Chkrememberme.Checked = true;
            txt_UserName.Focus();
            Session.Clear();
            strSetAlert = strSetAlert + "<script language='javascript'>";
            strSetAlert = strSetAlert + "MaxLengthh('" + rm.GetString("Alert_MaximumLengthis", ci) + "');";
            strSetAlert = strSetAlert + "</script>";
            Page.RegisterStartupScript("MaxLengthh", strSetAlert);
            string str;
            string url = Request.Url.AbsoluteUri;
            Session["HostServerURL"] = url;
            UriBuilder builder = new UriBuilder(Request.Url.Scheme, Request.Url.Host, Request.Url.Port, Request.Url.AbsolutePath);
            str = Convert.ToString(builder);
            Session["HostServerURL"] = str;
            RedirectToApprovalPage();
        }
        CultureInfo cultureInfo = new CultureInfo("en-us");
        cultureInfo.DateTimeFormat.ShortDatePattern = "MM/dd/yyyy";
        System.Threading.Thread.CurrentThread.CurrentCulture = cultureInfo;
        //LDAP
        if (!IsPostBack)
        {
            DomainValidation();
        }

        //LoadUTCTime();
    }

    //private void LoadUTCTime()
    //{
    //    DataSet ds_UTC = new DataSet();
    //    org_levelsEventData getUtc = new org_levelsEventData();
    //    ds_UTC = getUtc.GetUTCTimeZone();
    //    ddlUTCTime.DataSource = ds_UTC;
    //    ddlUTCTime.DataTextField = "CountryName";
    //    ddlUTCTime.DataValueField = "TimeZoneID"; 
    //    ddlUTCTime.DataBind();
    //    //ddlUTCTime.Items.Insert(0, new ListItem("-Select-", "0"));
    //    //ddlUTCTime.Items.Add("-Select-");
    //    //ddlUTCTime.SelectedValue = "-Select-";
    //    ddlUTCTime.Dispose();


    //}


    /// <summary>
    /// Redirect To Approval Page directly if request is came from mail link Otherwise redirect to dashboard screen.
    /// </summary>
    private void RedirectToApprovalPage()
    {
        if (Convert.ToString(Request.QueryString["ApprovalType"]) != null && Convert.ToString(Request.QueryString["ApprovalType"]) != string.Empty)
        {
            if (Convert.ToString(Request.QueryString["Angler"]) != null && Convert.ToString(Request.QueryString["Angler"]) != string.Empty)
                payrollConfig = 1;
            else
                payrollConfig = 0;
            string LevelId = string.Empty;
            switch (Convert.ToString(Request.QueryString["ApprovalType"]))
            {
                case "TimesheetEntry":
                    Session["SanctionUrl"] = "Transactions/TA_UI_Transaction_Sanctions.aspx?ApprovalType=" + Request.QueryString["ApprovalType"];
                    break;
                case "Leave":
                    switch (payrollConfig)
                    {
                        case 0:
                            Session["SanctionUrl"] = "Transactions/TA_UI_Transactions_LeaveSanctionModify.aspx?LeaveApplication_Id=" + Request.QueryString["LeaveApplication_Id"] + "&LevelId=" + Request.QueryString["LevelId"] + "&Status=" + Request.QueryString["Status"] + "&From_Date=&To_Date=&strSwipeCardNo=&strEmployeeName=&strEmployeeCodeId=&ApprovalType=" + Request.QueryString["ApprovalType"];
                            break;
                        default:
                            Session["SanctionUrl"] = "Transactions/TA_UI_Transactions_LeaveSanctionModify_Angler.aspx?LeaveApplication_Id=" + Request.QueryString["LeaveApplication_Id"] + "&LevelId=" + Request.QueryString["LevelId"] + "&Status=" + Request.QueryString["Status"] + "&From_Date=&To_Date=&strSwipeCardNo=&strEmployeeName=&strEmployeeCodeId=&ApprovalType=" + Request.QueryString["ApprovalType"];
                            break;
                    }
                    break;
                case "Onduty":
                    if (Request.QueryString["ParentID"] != null)
                    {
                        int companyId = 0;
                        org_levelsEventData getOrg = new org_levelsEventData();
                        getOrg.GetOrgParentLevels_FromID(Convert.ToInt32(Request.QueryString["LevelID"]));
                        DataSet ds_getOrg = new DataSet();
                        ds_getOrg = getOrg.GetOrgParentLevels();
                        if (ds_getOrg != null)
                        {
                            if (ds_getOrg.Tables[0].Rows.Count > 0)
                            {
                                companyId = Convert.ToInt32(ds_getOrg.Tables[0].Rows[0]["LevelID"].ToString());
                            }
                        }
                        LevelId = rptcommon.getNodes(companyId, Convert.ToString(Request.QueryString["LevelID"]));
                        Session["parentLevelId"] = companyId;
                    }
                    Session["SanctionUrl"] = "Transactions/TA_UI_Transactions_OnDutySanctionModify.aspx?ODID=" + Request.QueryString["ODID"];
                    break;
                case "OnDutyBulk":
                    if (Request.QueryString["ParentID"] != null)
                    {
                        LevelId = rptcommon.getNodes(Convert.ToInt32(Request.QueryString["ParentID"]), Convert.ToString(Request.QueryString["LevelID"]));
                        Session["parentLevelId"] = Convert.ToInt32(Request.QueryString["ParentID"]);
                    }
                    else
                    {
                        LevelId = rptcommon.getNodes(Convert.ToInt32(Session["parentLevelId"]), Convert.ToString(Session["LevelRights"]));
                    }
                    Session["SanctionUrl"] = "Transactions/TA_UI_Transactions_OnDutySanctionViewForBulkApproval.aspx?ApprovalType=OnDutyBulk&EmpId=" + Convert.ToString(Request.QueryString["SwipeCard"]) + "&EmpName=&EmpCategory=" + Convert.ToInt32(Request.QueryString["EmpCategory"].ToString()) + "&EmpType=" + Convert.ToInt32(Request.QueryString["EmpType"].ToString()) + "&FromDate=" + Request.QueryString["FromDate"].ToString() + "&ToDate=" + Request.QueryString["ToDate"].ToString() + "&Status=" + Request.QueryString["Status"] + "&SwipeCard=&ParentID=" + Convert.ToInt32(Request.QueryString["ParentID"]) + "&LevelID=" + LevelId + "";
                    break;
                case "Permission":
                    switch (payrollConfig)
                    {
                        case 0:
                            Session["SanctionUrl"] = "Transactions/TA_UI_Transactions_PermissionSanctionModify.aspx?Permission_Id=" + Request.QueryString["Permission_Id"] + "&LevelId=" + Request.QueryString["LevelId"] + "&Status=" + Request.QueryString["Status"] + "&From_Date=&To_Date=&strSwipeCardNo=&strEmployeeName=&strEmployeeCodeId=";
                            break;
                        default:
                            Session["SanctionUrl"] = "Transactions/TA_UI_Transactions_PermissionSanctionModify_Angler.aspx?Permission_Id=" + Request.QueryString["Permission_Id"] + "&LevelId=" + Request.QueryString["LevelId"] + "&Status=" + Request.QueryString["Status"] + "&From_Date=&To_Date=&strSwipeCardNo=&strEmployeeName=&strEmployeeCodeId=";
                            break;
                    }
                    break;
            }
        }
    }
    private void loadco()
    {
        //string strDecryptedString = Cryptographys.Cryptography.Decrypt("gDyjbM1uuafR8MjoKX5wwi23GybtIacbzvHrzlcx+fvFzuPBdm6uOGEVQGXydZNkg9IRkdGLY58Ci+HxeRjexGUsxZ/CUTmdQvl0CJZwJb7eV/ILlL1gow==", "TimecheckPhaseI");
        StringBuilder sbConnection = new StringBuilder();
        sbConnection.Append("Data Source=");
        sbConnection.Append(@"LENOVO\BSSERVER");
        sbConnection.Append(";Initial Catalog=");
        sbConnection.Append("TimecheckNew");
        sbConnection.Append(";User ID=");
        sbConnection.Append("Timecheck");
        sbConnection.Append(";pwd=");
        sbConnection.Append("timecheck");
        sbConnection.Append(";");
        string strEncryptedConString = Cryptography.Encrypt(sbConnection.ToString(), "TimecheckPhaseI");
    }
    #endregion
    #region DomainValidation
    /// <summary>
    /// Validate Domain
    /// LDAP
    /// </summary>
    private void DomainValidation()
    {
        if (Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["LDAPrequired"]) == "1")
        {
            isDomainLoginRequired = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["LDAPrequired"]);
            isDomainLoginRequiredflag = true;
            //ViewState["isDomainLoginRequired"] = isDomainLoginRequired;
            Session["isDomainLoginRequiredflag"] = ViewState["isDomainLoginRequiredflag"] = isDomainLoginRequiredflag;
            string DomainName = "";
            string DomainUserName = "";
            string DomainUserPwd = "";
            if (Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["LDAPDomainName"]) != "")
                DomainName = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["LDAPDomainName"]);
            if (Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["LDAAuthenticalUser"]) != "")
                DomainUserName = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["LDAAuthenticalUser"]);
            if (Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["LDAAuthenticalUserPwd"]) != "")
            {
                DomainUserPwd = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["LDAAuthenticalUserPwd"]);
                DomainUserPwd = Cryptographys.Cryptography.Decrypt(DomainUserPwd, "TimecheckPhaseI");
            }
            if (DomainName != "" && DomainUserName != "" && DomainUserPwd != "")
            {
                try
                {
                    currentSystemloginuserName = HttpContext.Current.User.Identity.Name.Split('\\')[1].ToString();
                    DirectoryEntry adFolderObject = new DirectoryEntry("LDAP://" + DomainName, DomainUserName, DomainUserPwd);
                    DirectorySearcher adSearcherObject = new DirectorySearcher(adFolderObject);
                    adSearcherObject.SearchScope = SearchScope.Subtree;
                    adSearcherObject.Filter = "(&(objectClass=user)(objectCategory=person)(SAMAccountName=" + currentSystemloginuserName + "))";
                    SearchResultCollection results;
                    results = adSearcherObject.FindAll();
                    if (results != null)
                        btn_Enter_Click(btn_Enter, null);
                }
                catch
                {
                }
            }
        }
    }
    #endregion
    #region UserFunction
    public void EncryptConnStr(string provider)
    {
        string protectionProvider = string.Empty;
        Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
        ConfigurationSection section = config.Sections["connectionStrings"];
        section.SectionInformation.ProtectSection(protectionProvider);
        config.Save();
    }
    public void DecryptConnStr()
    {
        Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
        ConfigurationSection section = config.Sections["connectionStrings"];
        section.SectionInformation.UnprotectSection();
        config.Save();
    }
    //LDAP
    private bool AuthenticateUserName(bool isDomain, string loginUserName)
    {
        try
        {
            if (isDomain == true && Convert.ToBoolean(ViewState["isDomainLoginRequiredflag"]) == true)
                ds_UserName = objCommon.UserAuthenticateDomain(loginUserName);
            else
            {
                strUsername = txt_UserName.Text;
                strPassword = EncryptNewPassword(txt_Password.Text);
                ds_UserName = objCommon.UserAuthenticate( strPassword , strUsername);
            }
            //LDAP
            count = 0;
            if (ds_UserName.Tables.Count > 0)
            {
                count = ds_UserName.Tables[0].Rows.Count;
                if (ds_UserName.Tables[0].Rows.Count > 0)
                {
                    UserName = Convert.ToString(ds_UserName.Tables[0].Rows[0][1]);
                    if (ds_UserName.Tables[0].Rows[0]["Photo"] != DBNull.Value && Convert.ToString(ds_UserName.Tables[0].Rows[0]["Photo"]) != "")
                    {
                        try
                        {
                            DirectoryInfo dir = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + "Masters");
                            FileInfo[] files = dir.GetFiles("*.bmp");
                            foreach (FileInfo file in files)
                            {
                                string str = AppDomain.CurrentDomain.BaseDirectory + "LoginImage\\";
                                File.Delete(str + Convert.ToString(file));
                            }
                            Random rnd = new Random();
                            string strPath = "LoginImage/" + Convert.ToString(ds_UserName.Tables[0].Rows[0][0]) + ".bmp";
                            string imagename = Convert.ToString(ds_UserName.Tables[0].Rows[0][0]) + ".bmp";
                            byte[] storedImage = (byte[])(ds_UserName.Tables[0].Rows[0]["Photo"]);
                            MemoryStream stream = new MemoryStream(storedImage);
                            System.Drawing.Image img = System.Drawing.Image.FromStream(stream);
                            img.Save(Server.MapPath(strPath));
                            img.Dispose();
                            Session["UserImage"] = imagename;
                        }
                        catch (Exception ex)
                        {
                            Message("Authenticate User Name Block 1 : <br>" + ex.ToString());
                        }
                    }
                    else
                        Session["UserImage"] = "defaultPhoto.png";
                }
                else
                    Session["UserImage"] = "defaultPhoto.png";
            }
            if (count == 1)
            {
                #region ChekcingUserAccountIsLocked
                dsLoginLock = ObjEmployeeEventData.GetLockLogin(txt_UserName.Text.Trim());
                if (dsLoginLock.Tables[0].Rows.Count > 0)
                {
                    if (Convert.ToString(dsLoginLock.Tables[0].Rows[0]["IsActive"]) != "True")
                    {
                        string LockedTime = Convert.ToString(dsLoginLock.Tables[0].Rows[0]["LockedTime"]);
                        DateTime currentTimeLock = DateTime.Now;
                        TimeSpan spanLock = currentTimeLock.Subtract(Convert.ToDateTime(LockedTime));
                        double loggedLockhrs = spanLock.TotalMinutes;
                        if (loggedLockhrs < 30)
                        {
                            Message(rm.GetString("Alert_Thisuseraccounthasbeenlocked", ci));
                            flag = false;
                            return flag;
                        }
                        else
                        {
                            IsActive = 1;
                            ObjEmployeeEventData.InsertUpdateLockLogin(txt_UserName.Text.Trim(), IsActive);
                        }
                    }
                }
                #endregion
                #region StoringUserDetailsIntoSessionVariables
                Session["user"] = UserName;
                if (Convert.ToString(ds_UserName.Tables[0].Rows[0]["Employee_Id"]) != "")
                    Session["EmpAutoID"] = Convert.ToString(ds_UserName.Tables[0].Rows[0]["Employee_Id"]);
                if (Convert.ToString(ds_UserName.Tables[0].Rows[0]["Employee_Code_Id"]) != "")
                    Session["EmployeeCodeId"] = Convert.ToString(ds_UserName.Tables[0].Rows[0]["Employee_Code_Id"]);
                if (Convert.ToString(ds_UserName.Tables[0].Rows[0]["EmailId"]) != "")
                    Session["loginEmailId"] = Convert.ToString(ds_UserName.Tables[0].Rows[0]["EmailId"]);
                //LDAP
                if (isDomain == true && Convert.ToBoolean(ViewState["isDomainLoginRequiredflag"]) == true)
                    Session["EmployeeId"] = Convert.ToString(ds_UserName.Tables[0].Rows[0]["Employee_Code_Id"]);
                else
                    Session["EmployeeId"] = txt_UserName.Text;
                if (ds_UserName.Tables[0].Rows[0]["UserGroup_Id"] != DBNull.Value)
                {
                    Session["userGroup_Id"] = ds_UserName.Tables[0].Rows[0]["UserGroup_Id"];
                    Session["Admin"] = null;
                }
                else
                {
                    Session["userGroup_Id"] = 0;
                }
                Session["IsDashboardEnable"] = "No";
                #region MyProfile
                if (Convert.ToString(ds_UserName.Tables[0].Rows[0]["IsMyProfileRqrd"]) != "")
                {
                    Session["IsMyProfileRqrd"] = Convert.ToString(ds_UserName.Tables[0].Rows[0]["IsMyProfileRqrd"]);
                }
                #endregion
                #endregion
                #region GettingMenuDetailsBasedonAssignedUsergroup_Employee
                DataSet ds = new DataSet();
                DataSet dsChildMenus = new DataSet();
                ds = objCommon.getUserMenu(0, Convert.ToInt32(Session["userGroup_Id"]), "");
                for (int iloop = 0; iloop <= ds.Tables[0].Rows.Count - 1; iloop++)
                {
                    if (Convert.ToInt32(ds.Tables[0].Rows[iloop]["PageID"]) == 179)
                    {
                        Session["IsDashboardEnable"] = "Yes";
                        break;
                    }
                }
                #endregion
                #region GetEmployeePreferredDateAndTime
                DataSet ds_DateTime = new DataSet();
                ds_DateTime = objshift.Select_DateandTimeFormat();
                if (ds_DateTime.Tables.Count > 0)
                {
                    if (ds_DateTime.Tables[0].Rows.Count > 0)
                    {
                        Session["IDateFormat"] = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings[Convert.ToString(ds_DateTime.Tables[0].Rows[0]["DateFormat"])]);
                        Session["ITimeFormat"] = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings[Convert.ToString(ds_DateTime.Tables[0].Rows[0]["TimeFormat"])]);
                        Session["MDateFormat"] = Convert.ToString(ds_DateTime.Tables[0].Rows[0]["DateFormat"]);
                        Session["MTimeFormat"] = Convert.ToString(ds_DateTime.Tables[0].Rows[0]["TimeFormat"]);
                        //LDAP
                    }
                }
                #endregion


                



                // Check user language
                int EmpID;
                EmpID = Convert.ToInt32(Session["EmpAutoID"]);
                #region GetPrevilegeDetails_Employee
                //Get Employee Grade Level
                Session["GradeLevel"] = ObjEmployeeEventData.SelectGradeLevel(Convert.ToString(EmpID));
                DataSet dsEmployeeGroup = new DataSet();
                dsEmployeeGroup = objLeaveApplicationEventData.GetEmployeeGroupName(Convert.ToInt32(Session["EmpAutoId"]));
                if (dsEmployeeGroup.Tables[0].Rows.Count > 0)
                {
                    Session["UserGroupName"] = Convert.ToString(dsEmployeeGroup.Tables[0].Rows[0]["GroupName"]);
                    Session["HasSpecialRights"] = Convert.ToString(dsEmployeeGroup.Tables[0].Rows[0]["hasSpecialRights"]);
                    Session["ReportsBasedOn"] = Convert.ToString(dsEmployeeGroup.Tables[0].Rows[0]["ReportsBasedOn"]);
                    Session["IndividualUsers"] = Convert.ToString(dsEmployeeGroup.Tables[0].Rows[0]["IndividualUsers"]);
                }
                #endregion
                #region GettingUserPreferredLanguageDetails
                dsEmployeeLingual = objMultiLingualEventData.GetEmployeeLingual(EmpID);
                if (dsEmployeeLingual.Tables[0].Rows.Count > 0)
                {
                    source_Language = "Resources." + Convert.ToString(dsEmployeeLingual.Tables[0].Rows[0]["Resource_File_Name"]);
                    Session["Session_ActiveLanguage"] = source_Language;
                    rm = new ResourceManager(source_Language, System.Reflection.Assembly.Load("App_GlobalResources"));
                    ci = Thread.CurrentThread.CurrentCulture;
                    Session["Direction"] = rm.GetString("Direction", ci);
                }
                else
                {
                    if (Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["DefaultLanguage"]) != "")
                    {
                        source_Language = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["DefaultLanguage"]);
                        Session["Session_ActiveLanguage"] = source_Language;
                        rm = new ResourceManager(source_Language, System.Reflection.Assembly.Load("App_GlobalResources"));
                        ci = Thread.CurrentThread.CurrentCulture;
                        Session["Direction"] = rm.GetString("Direction", ci);
                    }
                }
                #endregion
                flag = true;
            }
            else
            {
                #region ClearSessionValueAndStoringLockingTime
                flag = false;
                Session["user"] = null;
                Session["EmployeeId"] = null;
                Session["EmpAutoID"] = null;
                Session["loginEmailId"] = null;
                Session["userGroup_Id"] = null;
                Session["Admin"] = null;
                Session["IDateFormat"] = null;
                Session["ITimeFormat"] = null;
                Session["MDateFormat"] = null;
                Session["MTimeFormat"] = null;
                Session["UserGroupName"] = null;
                Session["HasSpecialRights"] = null;
                Session["IndividualUsers"] = null;
                Session["HasSpecialRights"] = null;
                Session["ReportsBasedOn"] = null;
                //LDAP
                if (isDomain == false && isDomainLoginRequiredflag == false)
                {
                    Message(rm.GetString("Alert_InvalidUserNameOrPassword", ci));
                    return false;
                }
                else
                {
                    Message("User account is not available in Timecheck");
                    //ViewState["isDomainLoginRequired"] = "1";
                    Session["isDomainLoginRequiredflag"] = ViewState["isDomainLoginRequiredflag"] = false;
                    return false;
                }
                //Check user name exists
                int UserCount = 0;
                int intNoOfTimes = 0;
                dsLoginLock = ObjEmployeeEventData.GetLockLogin(txt_UserName.Text.Trim());
                if (dsLoginLock.Tables[0].Rows.Count > 0)
                {
                    if (Convert.ToString(dsLoginLock.Tables[0].Rows[0]["IsActive"]) == "False")
                    {
                        string LockedTime = Convert.ToString(dsLoginLock.Tables[0].Rows[0]["LockedTime"]);
                        DateTime currentTimeLock = DateTime.Now;
                        TimeSpan spanLock = currentTimeLock.Subtract(Convert.ToDateTime(LockedTime));
                        double loggedLockhrs = spanLock.TotalMinutes;
                        if (loggedLockhrs < 30)
                        {
                            Message(rm.GetString("Alert_Thisuseraccounthasbeenlocked", ci));
                            return flag;
                        }
                    }
                }
                UserCount = ObjEmployeeEventData.GetUserNameExists(txt_UserName.Text.Trim());
                if (UserCount > 0)
                {
                    if (hdnUserName.Value == txt_UserName.Text.Trim())
                    {
                        if (Convert.ToString(hdnNoOfTimes.Value) != "")
                            intNoOfTimes = Convert.ToInt32(hdnNoOfTimes.Value);
                        intNoOfTimes = intNoOfTimes + 1;
                        hdnNoOfTimes.Value = Convert.ToString(intNoOfTimes);
                    }
                    else
                        hdnUserName.Value = "";
                    if (intNoOfTimes > 6)
                    {
                        IsActive = 0;
                        ObjEmployeeEventData.InsertUpdateLockLogin(txt_UserName.Text.Trim(), IsActive);
                    }
                    hdnUserName.Value = txt_UserName.Text.Trim();
                }
                #endregion
            }

        }
        catch (Exception ex)
        {
            Message("Authenticate User Name Block 2 : " + ex.ToString());
        }
        if (flag == true)
        {
            return true;
        }
        else
        {
            return false;
        }








    }
    // Encoding Password
    public string EncryptNewPassword(string EPassword)
    {
        MD5 md5 = MD5.Create();
        inputBytes = Encoding.ASCII.GetBytes(EPassword);
        hashBytes = md5.ComputeHash(inputBytes);
        EPassword = Convert.ToBase64String(hashBytes);
        return EPassword;
    }
    //Getting Information from resource file and display it in label
    private void LoadStrings(CultureInfo ci)
    {
        btn_Enter.Text = rm.GetString("btn_Enter", ci);
        btn_GetPwd.Text = rm.GetString("Caption_GetPassword", ci);
    }
    public string GenerateNewPassword()
    {
        int intMaxlength = 10;
        string PasswordChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
        string strPass = "";
        Random ObjRandom = new Random();
        for (int x = 0; x < intMaxlength; x++)
        {
            int i = Convert.ToInt32(Math.Floor(Convert.ToDouble(ObjRandom.Next(30))));
            strPass += PasswordChars[i];
        }
        return strPass;
    }
    public int ChangePassword(string EmployeeId, string EncryptPassword)
    {
        int count = 0;
        count = obj_ResetPwd.ResetPassword(EmployeeId, EncryptPassword);
        return count;
    }
    private bool sendEmailToEmployee(string ToEmailId, string Password, string strEmployeename, string StrEmployeecode)
    {
        bool isSendEmail = false;
        try
        {
            DataSet ds_DateTime = new DataSet();
            ds_DateTime = objshift.Select_DateandTimeFormat();
            if (ds_DateTime.Tables.Count > 0)
            {
                Session["MDateFormat"] = Convert.ToString(ds_DateTime.Tables[0].Rows[0]["DateFormat"]);
            }
            else
            {
                Session["MDateFormat"] = "MM/dd/yyyy";
            }
            string CurrentDate = string.Empty;
            CurrentDate = DateTime.Now.ToString(Convert.ToString(Session["MDateFormat"]));
            string EmailContent;
            MailMessage mailMessage = new MailMessage();
            mailMessage.From = new MailAddress(ConfigurationManager.AppSettings.Get("FromId"));
            mailMessage.To.Add(new MailAddress(ToEmailId));
            mailMessage.Subject = "Temporary Password for Timecheck Application - " + CurrentDate + " | " + StrEmployeecode + " - " + strEmployeename;
            EmailContent = "<b> Dear " + strEmployeename + ",</b> <br /><br />Your Temporary Password is : " + Password + "<br /><br /><b>Regards</b><br /> TimeCheck Administrator <br /> ";
            mailMessage.Body = EmailContent;
            objCommon.SendMail(mailMessage);
            isSendEmail = true;
        }
        catch (Exception ex)
        {
            isSendEmail = false;
        }
        return isSendEmail;
    }
    #region Message.
    private void Message(string messageContent)
    {
        string strScript = "<script language='javascript' type='text/javascript'>";
        strScript += "alert('" + messageContent.Replace("'", " ").Replace("\n", "").Replace("\r", "") + "');";
        strScript += " </script>";
        this.RegisterStartupScript("setScript", strScript);
    }
    #endregion
    #region MessageWithRedirect.
    private void MessageWithRedirect(string messageContent, string ToPage)
    {
        string strScript = "<script language='javascript' type='text/javascript'>";
        strScript += "alert('" + messageContent.Replace("'", " ").Replace("\n", "").Replace("\r", "") + "');";
        strScript += "location.href='" + ToPage + "';";
        strScript += " </script>";
        this.RegisterStartupScript("setScript", strScript);
    }
    #endregion
    #region Online License Updation
    public void InsertDetails(string CustomerName, string VersionType, string ToMailID, string CCmailID, string filename, string EmployeeEmail)
    {
        // save uploaded license file
        bool previousLicenseSE = false;
        string licenseFileName = string.Empty;
        string strFilePath = Convert.ToString(Server.MapPath("~\\LicenseFile"));
        System.IO.FileInfo fileInfo = new System.IO.FileInfo(strFilePath + "\\" + filename);
        // read license key and value to authenticate license
        string licenseValue = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["LicenseKey"]);
        if (licenseValue == "LicenseFile")
        {
            licenseFileName = strFilePath + "\\" + filename;
            //File Stream pointing to License File,if exist
            FileStream licenseFileStream = new FileStream(licenseFileName, FileMode.Open);
            //Stream Reader pointing to License  File
            StreamReader licenseFileStreamReader = new StreamReader(licenseFileStream);
            // read license file information from .lic file
            string encryptedLicFileInfo = licenseFileStreamReader.ReadToEnd();
            //Close the Streams
            licenseFileStreamReader.Close();
            licenseFileStream.Close();
            string decryptedLicFileInfo = Encryption.Decrypt(encryptedLicFileInfo, "");
            string[] decryptedLicFileInfoArr = decryptedLicFileInfo.Split('#');
            // set basic license info 
            string basicLicInfo = Convert.ToString(decryptedLicFileInfoArr[0]);
            string[] basicLicInfoArr = basicLicInfo.Split(',');
            // set license file MACAddress
            string macAddressLicFile = Convert.ToString(basicLicInfoArr[5]);
            string localMACAdderss = GetMACAddress();
            // check local and license file MACAddress
            if (macAddressLicFile != localMACAdderss)
            {
                return;
            }
            else
            {
                //Code added here by prabakaran.p                                    
                string[] fileArrDelete;
                int arrCountDelete = 0;
                //if (Session["Edition"].ToString() == "0" || Session["Edition"].ToString() == "3")
                //{
                if (Convert.ToString(basicLicInfoArr[1]) == "1")
                {
                    DataSet dsPendingForwarded = new DataSet();
                    dsPendingForwarded = objLicense.SelectLICPendingForwardedRecords();
                    if (dsPendingForwarded.Tables[0].Rows.Count > 0)
                    {
                        string strStatus = string.Empty;
                        strStatus = Convert.ToString(dsPendingForwarded.Tables[0].Rows[0]["Result"]);
                        if (strStatus != string.Empty)
                        {
                            fileArrDelete = Directory.GetFiles(Server.MapPath("~\\LicenseFile"), "*.lic");
                            arrCountDelete = fileArrDelete.Length;
                            if (arrCountDelete > 0)
                            {
                                for (int i = 0; i < arrCountDelete; i++)
                                {
                                    string strlicenseFileName = Convert.ToString(fileArrDelete[i]);
                                    if (strlicenseFileName == licenseFileName)
                                    {
                                        System.IO.FileInfo fileInfoDelete = new System.IO.FileInfo(strlicenseFileName);
                                        fileInfoDelete.Delete();
                                    }
                                }
                            }
                            // check demo expiry date
                            // if expired alert and do the login process to do pending, forwared to be approved
                            bool isDemoExpired = CheckDemo();
                            if (isDemoExpired)
                            {
                                // concurrent user updation
                                bool isLogin = ConcurrentUserUpdation();
                                if (isLogin)
                                {
                                    //To get Last login and Logout time of the specified user               
                                    DataSet dsLastLogin = new DataSet();
                                    dsLastLogin = ObjEmployeeEventData.GetLastLoginTime(Convert.ToString(Session["EmployeeId"]));
                                    string strLastLogin = string.Empty;
                                    string strLastLogout = string.Empty;
                                    if (dsLastLogin.Tables[0].Rows.Count > 0)
                                    {
                                        if (dsLastLogin.Tables[0].Rows[0]["LastLoginTime"] != DBNull.Value)
                                        {
                                            strLastLogin = Convert.ToString(dsLastLogin.Tables[0].Rows[0]["LastLoginTime"]);
                                        }
                                        if (dsLastLogin.Tables[0].Rows[0]["LastLogoutTime"] != DBNull.Value)
                                        {
                                            strLastLogout = Convert.ToString(dsLastLogin.Tables[0].Rows[0]["LastLogoutTime"]);
                                        }
                                    }
                                    Session["LastLoginTime"] = strLastLogin;
                                    Session["LastLogoutTime"] = strLastLogout;
                                    //Insert or Update Login Time in database table
                                    try
                                    {
                                        ObjEmployeeEventData.InsertUpdateLastLogin(Convert.ToString(Session["EmployeeId"]));
                                    }
                                    catch (Exception ex)
                                    {
                                        Message("Insert Details Block: " + ex.ToString());
                                    }
                                    DataSet dsUserGroup = new DataSet();
                                    dsUserGroup = objCommon.SelectGroupName(Convert.ToInt32(Session["userGroup_Id"]));
                                    if (dsUserGroup != null)
                                    {
                                        if (dsUserGroup.Tables.Count > 0)
                                        {
                                            if (dsUserGroup.Tables[0].Rows.Count > 0)
                                            {
                                                Session["UserGroupName"] = Convert.ToString(dsUserGroup.Tables[0].Rows[0]["groupName"]);
                                                Session["HasSpecialRights"] = Convert.ToString(dsUserGroup.Tables[0].Rows[0]["hasSpecialRights"]);
                                                Session["IndividualUsers"] = Convert.ToString(dsUserGroup.Tables[0].Rows[0]["IndividualUsers"]);
                                            }
                                        }
                                    }
                                    MessageWithRedirect(strStatus, "Landing.aspx");
                                    return;
                                }
                                else
                                {
                                    return;
                                }
                            }
                            else
                            {
                                Message(strStatus);
                                return;
                            }
                        }
                    }
                }
                //}
                fileArrDelete = Directory.GetFiles(Server.MapPath("~\\LicenseFile"), "*.lic");
                arrCountDelete = fileArrDelete.Length;
                if (arrCountDelete > 0)
                {
                    for (int i = 0; i < arrCountDelete; i++)
                    {
                        string strlicenseFileName = Convert.ToString(fileArrDelete[i]);
                        if (strlicenseFileName != licenseFileName)
                        {
                            if (strlicenseFileName.Contains("TA_LIC_SE"))
                            {
                                previousLicenseSE = true;
                            }
                            System.IO.FileInfo fileInfoDelete = new System.IO.FileInfo(strlicenseFileName);
                            fileInfoDelete.Delete();
                        }
                    }
                }
                // update db
                string customerId, packageId, noOfConcurrentUser, noOfEmployee, noOfTerminal, packageVersion, licenseGenerationDate, expiryDate;
                customerId = Convert.ToString(basicLicInfoArr[0]);
                string ecustomerId = Encryption.Encrypt(customerId, "");
                packageId = Convert.ToString(basicLicInfoArr[1]);
                string epackageId = Encryption.Encrypt(packageId, "");
                packageVersion = Convert.ToString(basicLicInfoArr[2]);
                string epackageVersion = Encryption.Encrypt(packageVersion, "");
                noOfConcurrentUser = Convert.ToString(basicLicInfoArr[3]);
                string enoOfConcurrentUser = Encryption.Encrypt(noOfConcurrentUser, "");
                noOfEmployee = Convert.ToString(basicLicInfoArr[4]);
                string enoOfEmployee = Encryption.Encrypt(noOfEmployee, "");
                string emacAddressLicFile = Encryption.Encrypt(macAddressLicFile, "");
                licenseGenerationDate = Convert.ToString(basicLicInfoArr[6]);
                string elicenseGenerationDate = Encryption.Encrypt(licenseGenerationDate, "");
                expiryDate = Convert.ToString(basicLicInfoArr[7]);
                string eexpiryDate = Encryption.Encrypt(expiryDate, "");
                noOfTerminal = Convert.ToString(basicLicInfoArr[8]);
                string enoOfTerminal = Encryption.Encrypt(noOfTerminal, "");
                // set module information
                //module = decryptedLicFileInfoArr[1].ToString();
                string emodule = "";
                //module1 = decryptedLicFileInfoArr[2].ToString();
                string emodule1 = "";
                //module2 = decryptedLicFileInfoArr[3].ToString();
                string emodule2 = "";
                //module3 = decryptedLicFileInfoArr[4].ToString();
                string emodule3 = "";
                //module4 = decryptedLicFileInfoArr[5].ToString();
                string emodule4 = "";
                //module5 = decryptedLicFileInfoArr[6].ToString();
                string emodule5 = "";
                // construct the data table with status true
                // and do bulk insert
                // after having status false pageid seperate to delete from user rights table
                string pageStatusFalse = string.Empty;
                // data table for TA_Tbl_Page
                DataTable dtPageInfo = new DataTable("TA_Tbl_Page");
                // datacolumn for TA_Tbl_Page columns
                DataColumn dcPageId = new DataColumn("pageId", System.Type.GetType("System.Double"));
                DataColumn dcDisplayName = new DataColumn("displayName", System.Type.GetType("System.String"));
                DataColumn dcPath = new DataColumn("path", System.Type.GetType("System.String"));
                DataColumn dcParentId = new DataColumn("parentId", System.Type.GetType("System.Int32"));
                DataColumn dcOrderBy = new DataColumn("orderBy", System.Type.GetType("System.Double"));
                DataColumn dcParentIdForSubMenu = new DataColumn("ParentIdForSubMenu", System.Type.GetType("System.Double"));
                // datacolumn adding to data table
                dtPageInfo.Columns.Add(dcPageId);
                dtPageInfo.Columns.Add(dcDisplayName);
                dtPageInfo.Columns.Add(dcPath);
                dtPageInfo.Columns.Add(dcParentId);
                dtPageInfo.Columns.Add(dcOrderBy);
                dtPageInfo.Columns.Add(dcParentIdForSubMenu);
                DataRow drPageInfo;
                string enterprisePageIds = string.Empty;
                string parenIds = string.Empty;
                for (int i = 0; i < decryptedLicFileInfoArr.Length; i++)
                {
                    if (i > 0)
                    {
                        // set module information
                        string moduleInfo = Convert.ToString(decryptedLicFileInfoArr[i]);
                        string[] decryptedModuleArr = moduleInfo.Split('*');
                        for (int j = 0; j < decryptedModuleArr.Length; j++)
                        {
                            string[] decryptedModuleColumnArr = Convert.ToString(decryptedModuleArr[j]).Split(',');
                            if (Convert.ToString(decryptedModuleColumnArr[3]) == "1")
                            {
                                drPageInfo = dtPageInfo.NewRow();
                                drPageInfo.BeginEdit();
                                drPageInfo["pageId"] = Convert.ToDouble(decryptedModuleColumnArr[1]);
                                drPageInfo["displayName"] = Convert.ToString(decryptedModuleColumnArr[4]);
                                drPageInfo["path"] = Convert.ToString(decryptedModuleColumnArr[5]);
                                drPageInfo["parentId"] = Convert.ToInt32(decryptedModuleColumnArr[2]);
                                drPageInfo["orderBy"] = Convert.ToDouble(decryptedModuleColumnArr[6]);
                                if (Convert.ToString(decryptedModuleColumnArr[7]) == string.Empty)
                                {
                                }
                                else
                                {
                                    drPageInfo["ParentIdForSubMenu"] = Convert.ToDouble(decryptedModuleColumnArr[7]);
                                }
                                drPageInfo.EndEdit();
                                dtPageInfo.Rows.Add(drPageInfo);
                                if (Convert.ToString(decryptedModuleColumnArr[2]) != "0")
                                {
                                    // collect the page ids in string to insert relevant user rights data                                 
                                    if (enterprisePageIds == string.Empty)
                                    {
                                        enterprisePageIds = Convert.ToString(decryptedModuleColumnArr[1]);
                                        parenIds = Convert.ToString(decryptedModuleColumnArr[2]);
                                    }
                                    else
                                    {
                                        enterprisePageIds = enterprisePageIds + "," + Convert.ToString(decryptedModuleColumnArr[1]);
                                        parenIds = parenIds + "," + Convert.ToString(decryptedModuleColumnArr[2]);
                                    }
                                }
                            }
                            else
                            {
                                // collect the page ids in string to delete relevant user rights data                                 
                                if (pageStatusFalse == string.Empty)
                                {
                                    pageStatusFalse = Convert.ToString(decryptedModuleColumnArr[1]);
                                }
                                else
                                {
                                    pageStatusFalse = pageStatusFalse + "," + Convert.ToString(decryptedModuleColumnArr[1]);
                                }
                            }
                        }
                    }
                }
                // insert the license details
                // in this sp delete all from TA_Tbl_Page,user rights table before insert basic details
                objLicense.InsertIntoProtectionTable(ecustomerId, epackageId, epackageVersion, enoOfConcurrentUser, enoOfEmployee, enoOfTerminal, emacAddressLicFile, elicenseGenerationDate, eexpiryDate, emodule, emodule1, emodule2, emodule3, emodule4, emodule5, pageStatusFalse);
                // insert into TA_Tbl_Page
                objLicense.InsertIntoTATblPage(dtPageInfo);
                // if license is standard edition 
                // insert default gradr SEGrade and get id of the same
                // and update id for all designations
                // and update 0 for all employees except '18000000'
                // delete grade except id
                int gradeMasterExists = 0;
                gradeMasterExists = objCommon.CheckPageExistsInLicense(228);
                if (packageId == "1" && gradeMasterExists == 0)
                {
                    objLicense.UpdateDefaultGradeForSE("SEGrade", 1, Convert.ToInt32(Session["EmpAutoID"]));
                }
                else
                {
                    if (previousLicenseSE)
                    {
                        // pass all enterprise pageids as string
                        // if pageid not in ta_tbl_userrights for superadmin 1
                        // then insert(ta_tbl_userrights) for superadmin rights as it is default
                        objLicense.UpdateDefaultRights(enterprisePageIds, parenIds, Convert.ToInt32(Session["EmpAutoID"]));
                    }
                }
                Base.BasePage objBase = new Base.BasePage();
                objBase.LogoutUsers();
            }
        }
    }
    #endregion
    public string GetMACAddress()
    {
        NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
        String sMacAddress = string.Empty;
        foreach (NetworkInterface adapter in nics)
        {
            if (sMacAddress == String.Empty)// only return MAC Address from first card  
            {
                IPInterfaceProperties properties = adapter.GetIPProperties();
                sMacAddress = adapter.GetPhysicalAddress().ToString();
            }
        }
        return sMacAddress;
    }
    private bool CheckDemo()
    {
        string strScript = "";
        string strInstalledDate = "";
        string strExpiryDate = "";
        //Check expiry date       
        strInstalledDate = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["Validate1"]);
        strExpiryDate = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["Validate2"]);
        strInstalledDate = Cryptography.Decrypt(strInstalledDate, "TimecheckPhaseI");
        strExpiryDate = Cryptography.Decrypt(strExpiryDate, "TimecheckPhaseI");
        DateTime dtExpDate = DateTime.Parse(strExpiryDate);
        if (DateTime.Compare(DateTime.Now.Date, dtExpDate) >= 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    private bool ConcurrentUserUpdation()
    {
        string strScript = "";
        Boolean Flag = true;
        cls_Common objCommon = new cls_Common();
        string licenseUptScript = "";
        bool status = true;
        DateTime inTime;
        // for concurrent user status checking - code added here                                                    
        ipAddress = Convert.ToString(Request.ServerVariables["REMOTE_ADDR"]);
        String strHostName;
        strHostName = Dns.GetHostName();
        IPHostEntry ipEntry = Dns.GetHostByName(strHostName);
        userId = Convert.ToString(Session["EmployeeId"]);
        DateTime loginTime = DateTime.Now;
        IPAddress[] addr = ipEntry.AddressList;
        session_Id = Convert.ToString(Session.SessionID);
        //Due to cache,its showing wrong count of concurrent user.
        //so we commented below line on 05-Feb-2020 12:34 PM
        //int cUserCount = HttpContext.Current.Cache.Count; // cache handling
        //string sActiveYearcUserCount = Convert.ToString(Cache["ActiveYearSetting"]);
        //if (sActiveYearcUserCount == null || sActiveYearcUserCount == String.Empty)
        //{
        //}
        //else
        //{
        //    cUserCount = cUserCount - 1;
        //}
        int cUserCount = 0; // cache handling
        string sActiveYearcUserCount = Convert.ToString(Cache["ActiveYearSetting"]);
        if (sActiveYearcUserCount == null || sActiveYearcUserCount == String.Empty)
        {
        }
        else
        {
            //cUserCount = cUserCount - 1;
            cUserCount = GetConcurrentUserCount(cUserCount);
        }
        // check concurrent user count
        if (cUserCount == 0)
        {
            // this could be a new "illegal" logon, so we need to check
            // if these credentials are already in the Cache	                                                                                               
            string sUser = Convert.ToString(Cache[userId.ToUpper()]);
            if (sUser == null || sUser == String.Empty)
            {
                // No Cache item, so sesion is either expired or user is new sign-on
                // Set the cache item and Session hit-test for this user---
                TimeSpan SessTimeOut = new TimeSpan(0, 0, HttpContext.Current.Session.Timeout, 0, 0);
                string userValue = string.Empty;
                userValue = Convert.ToString(ipAddress) + "," + loginTime + "," + session_Id;
                HttpContext.Current.Cache.Insert(userId.ToUpper(), userValue, null, DateTime.MaxValue, SessTimeOut, System.Web.Caching.CacheItemPriority.NotRemovable, null); // cache handling
                // cache user name
                Session["cUserName"] = userId.ToUpper();
                return true;
            }
        }
        else
        {
            // check user is already loggedin            
            string sUser = Convert.ToString(Cache[userId.ToUpper()]);
            if (sUser != null && sUser != String.Empty)
            {
                Message("User is currently logged in an another session. If you want kill that session Press Proceed!");
                return false;
            }
            else
            {
                // check count of concurrent user      
                // for concurrent user not more than 3
                // int concurrentUserCount = objCommon.CheckConcurrentUserCount();
                int concurrentUserCount = 0;
                //Commented on 05-Feb-2020 due to wrong value .
                //concurrentUserCount = HttpContext.Current.Cache.Count;
                string sActiveYear = Convert.ToString(Cache["ActiveYearSetting"]);
                if (sActiveYear == null || sActiveYear == String.Empty)
                {
                }
                else
                {
                    //concurrentUserCount = concurrentUserCount - 1;
                    concurrentUserCount = GetConcurrentUserCount(concurrentUserCount);
                }
                if (userId.ToLower() != "admin" && concurrentUserCount >= 3)
                {
                    MessageWithRedirect("Cannot Login, Maximum No. of Concurrent user count is reached!", "index.aspx");
                    return false;
                }
                else
                {
                    // valid user, but not login yet, now want to login                                        
                    TimeSpan SessTimeOut = new TimeSpan(0, 0, HttpContext.Current.Session.Timeout, 0, 0);
                    string userValue = string.Empty;
                    userValue = Convert.ToString(ipAddress) + "," + loginTime + "," + session_Id;
                    HttpContext.Current.Cache.Insert(userId.ToUpper(), userValue, null, DateTime.MaxValue, SessTimeOut, System.Web.Caching.CacheItemPriority.NotRemovable, null); // cache handling
                    // cache user name
                    Session["cUserName"] = userId.ToUpper();
                    return true;
                }
            }
        }
        return true;
    }
    private int GetConcurrentUserCount(int concurrentUserCount)
    {
        DictionaryEntry de = new DictionaryEntry();
        string strCacheData = "";
        foreach (object obj in Cache)
        {
            de = (DictionaryEntry)obj;
            if (de.Key.ToString() != "ActiveYearSetting")
            {
                strCacheData = de.Value.ToString();
                string[] strData = strCacheData.Split(',');
                if (strData.Length > 1)
                {
                    concurrentUserCount = concurrentUserCount + 1;
                }
            }
        }
        return concurrentUserCount;
    }
    #endregion
    #region ButtonClick
    protected void btn_Enter_Click(object sender, EventArgs e)
    {
        try
        {
            //String UTC =ddlUTCTime.SelectedItem.Value;
            //Session["UTCTimeID"] = "";
            //Session["UTCTimeID"] = UTC;


            //if (UTC == "-Select-")
            //{
            //    strSetAlert = strSetAlert + "<script language='javascript'>";
            //    strSetAlert = strSetAlert + "alert('" + rm.GetString("Alert_UTCTimeValidation", ci) + "');";
            //    strSetAlert = strSetAlert + "</script>";
            //    Page.RegisterStartupScript("Error", strSetAlert);
            //}
            //else
            //{


            Session["LastLoginTime"] = string.Empty;
            Session["LastLogoutTime"] = string.Empty;
            Session["ActiveEmployee"] = "5";
            string strDBExists = "0";
            // user authentication
            bool userAuthentication = false;
            //Check the Database connection information is valid
            string strDecryptedConnectionString = string.Empty;
            strDecryptedConnectionString = Cryptographys.Cryptography.GetDecryptedConnectionString();
            strDBExists = objCommon.CheckDatabaseExists(strDecryptedConnectionString);
            if (strDBExists == "0" || strDecryptedConnectionString == string.Empty)
            {
                Response.Redirect("TA_UI_Database_Configuration.aspx");
                return;
            }
            else if (strDBExists == "1")
            {
            }
            else
            {
                Message(strDBExists);
                return;
            }
            if (Convert.ToBoolean(ViewState["isDomainLoginRequiredflag"]) == true)
                userAuthentication = AuthenticateUserName(true, currentSystemloginuserName);
            else
                userAuthentication = AuthenticateUserName(false, "");
            // user authentication
            if (userAuthentication == true)
            {

                //#region UTC Time Save
                //String EmployeeID = Convert.ToString(Session["EmpAutoID"]);
                //org_levelsEventData getUtcEmployeeCheck = new org_levelsEventData();
                //DataSet ds_UTC = new DataSet();
                //ds_UTC = getUtcEmployeeCheck.GetUTCTimeZoneEmployeeCheck(Convert.ToInt32(EmployeeID));
                //int Counts = ds_UTC.Tables[0].Rows.Count;
                //String UTC = Convert.ToString(Session["UTCTimeID"]);
                //if (Counts == 0)
                //{
                //    org_levelsEventData getUtcI = new org_levelsEventData();
                //    if (Convert.ToString(UTC) == "-Select-")
                //    {
                       
                //        string script = "<script>alert('Select Your TimeZone First Time Log In');</script>";
                //        ScriptManager.RegisterStartupScript(this, GetType(), "PopupScript", script, false);

                //    }
                //    else
                //    {
                //        getUtcI.UTCEmployeeDetailsInsert(Convert.ToInt32(EmployeeID), Convert.ToInt32(UTC), DateTime.UtcNow, 1);
                //    }
                    

                //}
                //else 
                //{
                //    String UTCCheck = Convert.ToString(ds_UTC.Tables[0].Rows[0]["EmployeeCode"].ToString());
                //    if (UTC == UTCCheck)
                //    {

                //    }
                //    else
                //    {
                //        if(Convert.ToString( UTC )== "-Select-")
                //        {
                //            string script = "<script>alert('Select Your TimeZone First Time Log In');</script>";
                //            ScriptManager.RegisterStartupScript(this, GetType(), "PopupScript", script, false);

                //        }
                //        else
                //        {
                //            org_levelsEventData getUtcU = new org_levelsEventData();
                //            int UTC_Auto_ID = Convert.ToInt32(ds_UTC.Tables[0].Rows[0]["UTC_Auto_ID"].ToString());
                //            getUtcU.UTCEmployeeDetailsUpdate(UTC_Auto_ID,Convert.ToInt32(UTC));

                //        }
                        

                //    }

                //}

                //#endregion
                DataSet ds_DateTime = new DataSet();
                ds_DateTime = objshift.Select_DateandTimeFormat();
                if (ds_DateTime.Tables.Count > 0)
                {
                    if (ds_DateTime.Tables[0].Rows.Count > 0)
                    {
                        Session["IDateFormat"] = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings[Convert.ToString(ds_DateTime.Tables[0].Rows[0]["DateFormat"])]);
                        Session["ITimeFormat"] = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings[Convert.ToString(ds_DateTime.Tables[0].Rows[0]["TimeFormat"])]);
                        Session["MDateFormat"] = Convert.ToString(ds_DateTime.Tables[0].Rows[0]["DateFormat"]);
                        Session["MTimeFormat"] = Convert.ToString(ds_DateTime.Tables[0].Rows[0]["TimeFormat"]);
                    }
                }
                Session["ApplnMode"] = "False";
                NodeLocking nodeLocking = new NodeLocking();
                string localMACAdderssForupdation = nodeLocking.VerifyMACAddress("");
                Session["localMACAdderssForlic"] = localMACAdderssForupdation;
                //Added for (Online License) updation of license file automatically if the expiry date reaches 5 days
                if (Convert.ToString(Session["EmpAutoID"]) == "1" && Convert.ToString(Session["UserGroupName"]) == "SuperAdmin")
                {
                    GetSetLicenseDetailse();
                }
                if (Chkrememberme.Checked == true)
                {
                    Response.Cookies["TCUName"].Value = txt_UserName.Text;
                    Response.Cookies["TCPwd"].Value = txt_Password.Text;
                    Response.Cookies["TCUName"].Expires = DateTime.Now.AddDays(15);
                    Response.Cookies["TCPwd"].Expires = DateTime.Now.AddDays(15);
                }
                else
                {
                    Response.Cookies["TCUName"].Expires = DateTime.Now.AddDays(-1);
                    Response.Cookies["TCPwd"].Expires = DateTime.Now.AddDays(-1);
                }
                GetShiftSettingAndLicEmployeeCountDetails();
            }
            else
            {
                return;
            }

            // }

        }

        catch (Exception ex)
        {
            Message(ex.ToString());
        }
    }
    protected void btn_License_Click(object sender, EventArgs e)
    {
        Response.Redirect("TA_UI_LicenseRequest.aspx");
    }
    protected void btn_ForgotPassword_Click(object sender, EventArgs e)
    {
        Response.Redirect("ForgotPassword.aspx");
    }
    protected void btn_Proceed_Click(object sender, EventArgs e)
    {
        processed();
    }
    private void processed()
    {
        // delete the Admin entry from TA_Tbl_ConcurrentUser
        if (Session["EmployeeId"] != null && Convert.ToString(Session["EmployeeId"]) != "")
        {
            string sUser = Convert.ToString(Cache[Convert.ToString(Session["EmployeeId"]).ToUpper()]);
            if (sUser != null && sUser != String.Empty)
            {
                ObjEmployeeEventData.InsertUpdateLastLogout(Convert.ToString(Session["EmployeeId"]));
                HttpContext.Current.Cache.Remove(Convert.ToString(Session["EmployeeId"]).ToUpper());
            }
            else
            {
                return;
            }
            // insert into TA_Tbl_ConcurrentUser
            ipAddress = Convert.ToString(Request.ServerVariables["REMOTE_ADDR"]);
            DateTime loginTime = DateTime.Now;
            TimeSpan SessTimeOut = new TimeSpan(0, 0, HttpContext.Current.Session.Timeout, 0, 0);
            string userValue = string.Empty;
            userId = Convert.ToString(Session["EmployeeId"]);
            userValue = Convert.ToString(ipAddress) + "," + loginTime + "," + Convert.ToString(Session.SessionID);
            HttpContext.Current.Cache.Insert(userId.ToUpper(), userValue, null, DateTime.MaxValue, SessTimeOut, System.Web.Caching.CacheItemPriority.NotRemovable, null); // cache handling
            // cache user name
            Session["cUserName"] = userId.ToUpper();
            //To get Last login and Logout time of the specified user               
            DataSet dsLastLogin = new DataSet();
            dsLastLogin = ObjEmployeeEventData.GetLastLoginTime(userId);
            string strLastLogin = string.Empty;
            string strLastLogout = string.Empty;
            if (dsLastLogin.Tables[0].Rows.Count > 0)
            {
                if (dsLastLogin.Tables[0].Rows[0]["LastLoginTime"] != DBNull.Value)
                {
                    strLastLogin = Convert.ToString(dsLastLogin.Tables[0].Rows[0]["LastLoginTime"]);
                }
                if (dsLastLogin.Tables[0].Rows[0]["LastLogoutTime"] != DBNull.Value)
                {
                    strLastLogout = Convert.ToString(dsLastLogin.Tables[0].Rows[0]["LastLogoutTime"]);
                }
            }
            Session["LastLoginTime"] = strLastLogin;
            Session["LastLogoutTime"] = strLastLogout;
            ObjEmployeeEventData.InsertUpdateLastLogin(userId);
            Session["ApplnMode"] = "True";
            DataSet dsUserGroup = new DataSet();
            cls_Common objCommon = new cls_Common();
            dsUserGroup = objCommon.SelectGroupName(Convert.ToInt32(Session["userGroup_Id"]));
            if (dsUserGroup != null)
            {
                if (dsUserGroup.Tables.Count > 0)
                {
                    if (dsUserGroup.Tables[0].Rows.Count > 0)
                    {
                        Session["UserGroupName"] = Convert.ToString(dsUserGroup.Tables[0].Rows[0]["groupName"]);
                        Session["HasSpecialRights"] = Convert.ToString(dsUserGroup.Tables[0].Rows[0]["hasSpecialRights"]);
                        Session["ReportsBasedOn"] = Convert.ToString(dsUserGroup.Tables[0].Rows[0]["ReportsBasedOn"]);
                        Session["IndividualUsers"] = Convert.ToString(dsUserGroup.Tables[0].Rows[0]["IndividualUsers"]);
                    }
                }
            }
            if (Request.QueryString["ScheduleId"] != null)
            {
                string URL = "Reports/TA_UI_Report_ReportViewer.aspx?" + Convert.ToString(Request.QueryString);
                Response.Redirect(URL, false);
            }
            else
                RedirectToLandingBasedOnLicense();
        }
    }
    protected void btn_GetPwd_Click(object sender, EventArgs e)
    {
        if (Convert.ToInt32(ConfigurationManager.AppSettings.Get("isRequiredEmail")) == 1)
        {
            string EmpCode = txt_EmployeeId.Text;
            bool isSendEmail = false;
            string strEmailId = string.Empty, strEmployeename = string.Empty, StrEmployeecode = string.Empty;
            DataSet dsEmployee = new DataSet();
            dsEmployee = objEmployeeEventData.SelectSelectEmailByEmpId(EmpCode);
            if (dsEmployee.Tables[0].Rows.Count > 0)
            {
                if (dsEmployee.Tables[0].Rows[0]["EmailId"] != DBNull.Value)
                {
                    strEmailId = Convert.ToString(dsEmployee.Tables[0].Rows[0]["EmailId"]);
                    strEmployeename = Convert.ToString(dsEmployee.Tables[0].Rows[0]["Employee_FirstName"]);
                    StrEmployeecode = Convert.ToString(dsEmployee.Tables[0].Rows[0]["Employee_code_ID"]);
                    string newPassword = GenerateNewPassword();
                    string encryptedPassword = EncryptNewPassword(newPassword);
                    int intPwd = ChangePassword(EmpCode, encryptedPassword);
                    if (intPwd >= 1)
                    {
                        isSendEmail = sendEmailToEmployee(strEmailId, newPassword, strEmployeename, StrEmployeecode);
                        if (isSendEmail)
                        {
                            lblMessage.Text = "New password for Timecheck has been sent to your email address";
                        }
                        else
                        {
                            lblMessage.Text = "Email is not send successfully!, please try again sometimes";
                        }
                        lblMessage.Style.Add("display", "block");
                        lblMessage.Style.Add("color", "Green");
                        txt_EmployeeId.Visible = false;
                        btn_GetPwd.Visible = false;
                        return;
                    }
                    else if (intPwd == 0)
                    {
                        lblMessage.Text = "Employee Id is not found";
                        lblMessage.Style.Add("display", "block");
                    }
                }
                else
                {
                    lblMessage.Text = "Mail id not available for the given employee ID";
                    lblMessage.Style.Add("display", "block");
                    return;
                }
            }
            else
            {
                lblMessage.Text = "Employee ID not found";
                lblMessage.Style.Add("display", "block");
                return;
            }
        }
        else
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('Email notification is not in enabled mode!, so please contact your administrator');", true);
            return;
        }
    }
    #endregion
    private void GetSetLicenseDetailse()
    {
        DataSet dsLicenseDetails = new DataSet();
        dsLicenseDetails = objLicense.SelectLicenseExpiryDate();
        if (dsLicenseDetails.Tables.Count > 0 && dsLicenseDetails.Tables[0].Rows.Count > 0)
        {
            string gstrLicenseExpiryDate = string.Empty;
            gstrLicenseExpiryDate = Encryption.Decrypt(Convert.ToString(dsLicenseDetails.Tables[0].Rows[0]["expirydate"]), "");
            TimeSpan ts = Convert.ToDateTime(gstrLicenseExpiryDate) - System.DateTime.Now;
            TimeSpan checkts = Convert.ToDateTime(gstrLicenseExpiryDate) - DateTime.UtcNow; 
            DateTime Chts = DateTime.UtcNow;

            //var afghanTimeZone = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");
            //var utcTime = TimeZoneInfo.ConvertTimeToUtc(new DateTime(1970, 1, 1), afghanTimeZone);


            //var dt = DateTime.UtcNow;
            //var tz = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
            //var localTimeInNewYork = TimeZoneInfo.ConvertTimeFromUtc(dt, tz);
            //TimeSpan checktss = Convert.ToDateTime(gstrLicenseExpiryDate) - Convert.ToDateTime(localTimeInNewYork);


            int differenceInDays = ts.Days;
            if (differenceInDays <= 5)
            {
                bool NetResult = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
                if (NetResult == true)
                {
                    Int64 RequestID = 0;
                    DataSet dsCheckRequestID = new DataSet();
                    dsCheckRequestID = objLicense.SelectLicenseRequestIDReactivation();
                    if (dsCheckRequestID.Tables.Count > 0)
                    {
                        if (dsCheckRequestID.Tables[0].Rows.Count > 0)
                        {
                            RequestID = Convert.ToInt64(dsCheckRequestID.Tables[0].Rows[0]["RequestID"]);
                            if (RequestID > 0)
                            {
                                DataSet dsLicenseActive = new DataSet();
                                dsLicenseActive = Objservices.LicenseActivate(Convert.ToInt32(RequestID), true);
                                if (dsLicenseActive.Tables.Count > 0)
                                {
                                    if (dsLicenseActive.Tables[0].Rows.Count > 0)
                                    {
                                        string EncryptData = Convert.ToString(dsLicenseActive.Tables[0].Rows[0]["EncryptData"]);
                                        string ToMailID = Convert.ToString(dsLicenseActive.Tables[0].Rows[0]["ToMailID"]);
                                        string CCmailID = Convert.ToString(dsLicenseActive.Tables[0].Rows[0]["CCMailID"]);
                                        string CustomerName = Convert.ToString(dsLicenseActive.Tables[0].Rows[0]["CustName"]);
                                        string VersionType = Convert.ToString(dsLicenseActive.Tables[0].Rows[0]["VersionType"]);
                                        string FileName = Convert.ToString(dsLicenseActive.Tables[0].Rows[0]["FileNames"]);
                                        string EmployeeEmail = Convert.ToString(dsLicenseActive.Tables[0].Rows[0]["EmployeeEmail"]);
                                        if (EncryptData != "")
                                        {
                                            string strFilePath = Convert.ToString(Server.MapPath("~\\LicenseFile"));
                                            string licenseFileName = strFilePath + "\\" + FileName;
                                            FileInfo file = new FileInfo(licenseFileName);
                                            if (file.Exists)//check file exsit or not and delete it to avoid overriding of license file
                                            {
                                                file.Delete();
                                            }
                                            StreamWriter writer = new StreamWriter(strFilePath + "\\" + FileName, true);
                                            writer.WriteLine(EncryptData);
                                            writer.Close();
                                            InsertDetails(CustomerName, VersionType, ToMailID, CCmailID, FileName, EmployeeEmail);
                                            objLicense.UpdateResponseDetails(RequestID, Convert.ToBoolean(false));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    private void GetShiftSettingAndLicEmployeeCountDetails()
    {
        DataSet dsShiftSettings = new DataSet();
        NodeLocking nodeLocking = new NodeLocking();
        dsShiftSettings = objShiftSettingsEventData.GetShiftSettings();
        if (dsShiftSettings != null)
        {
            if (dsShiftSettings.Tables.Count > 0)
            {
                if (dsShiftSettings.Tables[0].Rows.Count > 0)
                {
                    Session["WeekStartDay"] = Convert.ToString(dsShiftSettings.Tables[0].Rows[0]["CumulativeWeekStartDay"]);
                    Session["WeekEndDay"] = Convert.ToString(dsShiftSettings.Tables[0].Rows[0]["CumulativeWeekEndDay"]);
                    Session["MonthStartDay"] = Convert.ToString(dsShiftSettings.Tables[0].Rows[0]["MonthStartDay"]);
                    Session["MonthEndDay"] = Convert.ToString(dsShiftSettings.Tables[0].Rows[0]["MonthEndDay"]);
                }
            }
        }
        // read license key and value to authenticate license
        string licenseValue = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["LicenseKey"]);
        if (licenseValue == "LicenseFile")
        {
            // handle soft license(license file)                                               
            //string[] fileArr= Directory.GetFiles(@"C:\", "*.lic");
            string[] fileArr = Directory.GetFiles(Server.MapPath("LicenseFile"), "*.lic");
            int arrCount = fileArr.Length;
            if (arrCount > 0)
            {
                string licenseFileName = Convert.ToString(fileArr[arrCount - 1]);
                //File Stream pointing to License File,if exist
                FileStream licenseFileStream = new FileStream(licenseFileName, FileMode.Open);
                //Stream Reader pointing to License  File
                StreamReader licenseFileStreamReader = new StreamReader(licenseFileStream);
                // read license request file information from .lrf file
                string encryptedLicFileInfo = licenseFileStreamReader.ReadToEnd();
                //Close the Streams
                licenseFileStreamReader.Close();
                licenseFileStream.Close();
                string decryptedLicFileInfo = string.Empty;
                try
                {
                    decryptedLicFileInfo = Encryption.Decrypt(encryptedLicFileInfo, "");
                }
                catch
                {
                    Message(rm.GetString("Alert_Licenseinformationarenotcorrect", ci));
                    flag = false;
                    return;
                }
                string[] decryptedLicFileInfoArr = decryptedLicFileInfo.Split('#');
                string basicLicInfo = Convert.ToString(decryptedLicFileInfoArr[0]);
                string[] basicLicInfoArr = basicLicInfo.Split(',');
                string customerIdLicFile = Convert.ToString(basicLicInfoArr[0]);
                string packageIdLicFile = Convert.ToString(basicLicInfoArr[1]);
                //Edition Assigning
                Session["Edition"] = packageIdLicFile;
                switch (packageIdLicFile)
                {
                    case "1":
                        Session["Demo"] = "Standard";
                        break;
                    case "2":
                        Session["Demo"] = "Express";
                        break;
                    default:
                        Session["Demo"] = "Enterprise";
                        break;
                }
                string packageVersionLicFile = Convert.ToString(basicLicInfoArr[2]);
                string[] split_packageID = Convert.ToString(packageVersionLicFile).Split('.');
                if (split_packageID != null)
                {
                    if (split_packageID.Length > 0)
                    {
                        if (split_packageID[0] != null)
                            Session["packageID"] = Convert.ToString(split_packageID[0]);
                        else
                            Session["packageID"] = 0;
                    }
                    else
                        Session["packageID"] = 0;
                }
                else
                    Session["packageID"] = 0;
                string noOfConcurrentUserLicFile = Convert.ToString(basicLicInfoArr[3]);
                string noOfEmployeeUserLicFile = Convert.ToString(basicLicInfoArr[4]);
                string macAddressLicFile = Convert.ToString(basicLicInfoArr[5]);
                string licenseGeneartionDateLicFile = Convert.ToString(basicLicInfoArr[6]);
                string expiryDateLicFile = Convert.ToString(basicLicInfoArr[7]);
                string noOfTerminalLicFile = Convert.ToString(basicLicInfoArr[8]);
                DateTime dtexpiryDateLicFile = Convert.ToDateTime(expiryDateLicFile);
                // get local machine's MACAddress                        
                string localMACAdderss = nodeLocking.VerifyMACAddress(macAddressLicFile);
                if (macAddressLicFile != localMACAdderss)
                {
                    Session["sLicNotSupport"] = "1";
                    if (Request.QueryString["ScheduleId"] != null)
                        Response.Redirect("Reports/TA_UI_Report_ReportViewer.aspx?" + Convert.ToString(Request.QueryString));
                    else
                        Response.Redirect("TA_UI_Valid.aspx");
                }
                else
                {
                    // objects creation for Licensing class
                    Licensing objLicense = new Licensing();
                    // get license information from protection table(TA_Tbl_LIC_Details)
                    // Macaddress of loggin Pc is First Readed and passed into this procedure this is modified for Moideen Tawazun Client
                    string local_MACAdderss = GetMACAddress();
                    local_MACAdderss = Encryption.Encrypt(local_MACAdderss, "");
                    DataSet dsLicenseInfo = new DataSet();
                    dsLicenseInfo = objLicense.SelectFromProtectionTable(local_MACAdderss);
                    string licenseUptScript = string.Empty;
                    if (dsLicenseInfo != null)
                    {
                        if (dsLicenseInfo.Tables.Count > 0)
                        {
                            if (dsLicenseInfo.Tables[0].Rows.Count > 0)
                            {
                                string dcustomerId, dpackageId, dnoOfConcurrentUser, dnoOfEmployee, dnoOfTerminal, dpackageVersion, dmacAddress, dlicenseGenerationDate, dexpiryDate, dmodule, dmodule1, dmodule2, dmodule3, dmodule4, dmodule5;
                                dcustomerId = Convert.ToString(dsLicenseInfo.Tables[0].Rows[0]["CustomerId"]);
                                string customerId = Encryption.Decrypt(dcustomerId, "");
                                dpackageId = Convert.ToString(dsLicenseInfo.Tables[0].Rows[0]["PackageId"]);
                                string packageId = Encryption.Decrypt(dpackageId, "");
                                dpackageVersion = Convert.ToString(dsLicenseInfo.Tables[0].Rows[0]["PackageVersion"]);
                                string packageVersion = Encryption.Decrypt(dpackageVersion, "");
                                dnoOfConcurrentUser = Convert.ToString(dsLicenseInfo.Tables[0].Rows[0]["NoOfConcurrentUser"]);
                                string noOfConcurrentUser = Encryption.Decrypt(dnoOfConcurrentUser, "");
                                dnoOfEmployee = Convert.ToString(dsLicenseInfo.Tables[0].Rows[0]["NoOfEmployee"]);
                                string noOfEmployee = Encryption.Decrypt(dnoOfEmployee, "");
                                dnoOfTerminal = Convert.ToString(dsLicenseInfo.Tables[0].Rows[0]["NoOfTerminal"]);
                                string noOfTerminal = Encryption.Decrypt(dnoOfTerminal, "");
                                dmacAddress = Convert.ToString(dsLicenseInfo.Tables[0].Rows[0]["MACAddress"]);
                                string macAddress = Encryption.Decrypt(dmacAddress, "");
                                dlicenseGenerationDate = Convert.ToString(dsLicenseInfo.Tables[0].Rows[0]["LicenseGenerationDate"]);
                                string licenseGenerationDate = Encryption.Decrypt(dlicenseGenerationDate, "");
                                dexpiryDate = Convert.ToString(dsLicenseInfo.Tables[0].Rows[0]["ExpiryDate"]);
                                string expiryDate = Encryption.Decrypt(dexpiryDate, "");
                                DateTime dtexpiryDate = Convert.ToDateTime(expiryDate);
                                //check license file information with protection table(TA_Tbl_Lic_Details)  
                                if (Convert.ToString(localMACAdderss) == "1A153492A74B" || Convert.ToString(localMACAdderss) == "00155D123773" || Convert.ToString(localMACAdderss) == "ECA86BFF8FBB")
                                {
                                    customerId = customerIdLicFile;
                                    packageId = packageIdLicFile;
                                    packageVersion = packageVersionLicFile;
                                    noOfConcurrentUser = noOfConcurrentUserLicFile;
                                    noOfEmployee = noOfEmployeeUserLicFile;
                                    macAddress = macAddressLicFile;
                                    dtexpiryDate = dtexpiryDateLicFile;
                                    licenseGenerationDate = licenseGeneartionDateLicFile;
                                    noOfTerminal = noOfTerminalLicFile;
                                }
                                if (customerId == customerIdLicFile && packageId == packageIdLicFile && packageVersion == packageVersionLicFile && noOfConcurrentUser == noOfConcurrentUserLicFile && noOfEmployee == noOfEmployeeUserLicFile && macAddress == macAddressLicFile && dtexpiryDate == dtexpiryDateLicFile && licenseGenerationDate == licenseGeneartionDateLicFile && noOfTerminal == noOfTerminalLicFile)
                                {
                                    // check no of employee validation
                                    DemoVersion objDemoVersion = new DemoVersion();
                                    int moduleDbCount = objDemoVersion.LicenseModuleCheck();
                                    int licModuleCount = 0;
                                    for (int i = 0; i < decryptedLicFileInfoArr.Length; i++)
                                    {
                                        if (i > 0)
                                        {
                                            // set module information
                                            string moduleInfo = Convert.ToString(decryptedLicFileInfoArr[i]);
                                            string[] decryptedModuleArr = moduleInfo.Split('*');
                                            for (int j = 0; j < decryptedModuleArr.Length; j++)
                                            {
                                                string[] decryptedModuleColumnArr = Convert.ToString(decryptedModuleArr[j]).Split(',');
                                                if (Convert.ToString(decryptedModuleColumnArr[3]) == "1")
                                                {
                                                    licModuleCount += 1;
                                                }
                                            }
                                        }
                                    }
                                    if (moduleDbCount > licModuleCount)
                                    {
                                        Session["sModuleExceeds"] = "1";
                                        Response.Redirect("TA_UI_Valid.aspx");
                                    }
                                    else
                                    {
                                        flag = true;
                                    }
                                    bool allowEmployeeAdd = false;
                                    int noOfEmployeeLicFile = Convert.ToInt32(noOfEmployeeUserLicFile);
                                    allowEmployeeAdd = objDemoVersion.LoginCheckEmployeeCreation("License", noOfEmployeeLicFile);
                                    objLicense.ActivateEmployeeBasedOnLicence(Convert.ToString(noOfEmployeeLicFile));
                                    Session["ActiveEmployee"] = Convert.ToString(noOfEmployeeLicFile);
                                    if (allowEmployeeAdd)
                                        flag = true;
                                    else
                                    {
                                        Session["sEmployeeAllow"] = "0";
                                        Response.Redirect("TA_UI_Valid.aspx");
                                    }
                                    int intNoOfTerminalLicFile = Convert.ToInt32(noOfTerminalLicFile);
                                    dtexpiryDateLicFile = dtexpiryDateLicFile.AddHours(-dtexpiryDateLicFile.Hour).AddMinutes(-dtexpiryDateLicFile.Minute).AddSeconds(-dtexpiryDateLicFile.Second);
                                    DateTime dtNow = DateTime.Parse(DateTime.Now.ToShortDateString());
                                    TimeSpan span = dtexpiryDateLicFile - dtNow;
                                    Session["sExpiryDays"] = span.Days;
                                    Session["sExpiryDate"] = objCommon.DateConvertion(Convert.ToString(Session["MDateFormat"]), dtexpiryDateLicFile.ToString(Convert.ToString(Session["MDateFormat"])));
                                    if ((span.Days <= 5) && (span.Days >= 0))
                                    {
                                        flag = true;
                                    }
                                    else if (span.Days < 0)
                                    {
                                        Response.Redirect("TA_UI_LicenseFileUpload.aspx");
                                    }
                                    else
                                    {
                                        flag = true;
                                    }
                                    ipAddress = Convert.ToString(Request.ServerVariables["REMOTE_ADDR"]);
                                    String strHostName;
                                    strHostName = Dns.GetHostName();
                                    IPHostEntry ipEntry = Dns.GetHostByName(strHostName);
                                    userId = Convert.ToString(Session["EmployeeId"]);
                                    DateTime loginTime = DateTime.Now;
                                    IPAddress[] addr = ipEntry.AddressList;
                                    string session_name = "a";
                                    session_Id = Convert.ToString(Session.SessionID);
                                    HttpCookie cookie_Session = new HttpCookie(session_name, session_Id);
                                    Response.Cookies.Add(cookie_Session);
                                    //Due to cache,its showing wrong count of concurrent user.
                                    //so we commented below line on 14-Feb-2020 13:30 PM
                                    int cUserCount = 0; // cache handling
                                    string sActiveYearcUserCount = Convert.ToString(Cache["ActiveYearSetting"]);
                                    if (sActiveYearcUserCount == null || sActiveYearcUserCount == String.Empty)
                                    {
                                    }
                                    else
                                    {
                                        cUserCount = GetConcurrentUserCount(cUserCount);
                                    }
                                    if (cUserCount != 0)
                                    {
                                        if (Convert.ToString(Session["IsDomain"]) == "0")
                                        {
                                            processed();
                                            cUserCount = 0;
                                        }
                                    }
                                    if (cUserCount == 0)
                                    {
                                        string sUser = Convert.ToString(Cache[userId.ToUpper()]);
                                        if (sUser == null || sUser == String.Empty)
                                        {
                                            TimeSpan SessTimeOut = new TimeSpan(0, 0, HttpContext.Current.Session.Timeout, 0, 0);
                                            string userValue = string.Empty;
                                            userValue = Convert.ToString(ipAddress) + "," + loginTime + "," + session_Id;
                                            HttpContext.Current.Cache.Insert(userId.ToUpper(), userValue, null, DateTime.MaxValue, SessTimeOut, System.Web.Caching.CacheItemPriority.NotRemovable, null); // cache handling
                                            Session["cUserName"] = userId.ToUpper();
                                            flag = true;
                                        }
                                    }
                                    else
                                    {
                                        string sUser = Convert.ToString(Cache[userId.ToUpper()]);
                                        if (sUser != null && sUser != String.Empty)
                                        {
                                            Message(rm.GetString("Alert_Useriscurrentlyloggedinananothersession", ci));
                                            btn_Proceed.Visible = true;
                                            btn_Enter.Visible = false;
                                            return;
                                        }
                                        else
                                        {
                                            int concurrentUserCount = 0;
                                            //Due to cache,its showing wrong count of concurrent user.
                                            //so we commented below line on 14-Feb-2020 13:30 PM
                                            //concurrentUserCount = HttpContext.Current.Cache.Count;
                                            string sActiveYear = Convert.ToString(Cache["ActiveYearSetting"]);
                                            if (sActiveYear == null || sActiveYear == String.Empty)
                                            {
                                            }
                                            else
                                            {
                                                concurrentUserCount = GetConcurrentUserCount(concurrentUserCount);
                                            }
                                            if (userId.ToLower() != "admin" && concurrentUserCount >= Convert.ToInt32(noOfConcurrentUserLicFile))
                                            {
                                                Message(rm.GetString("Alert_CannotLoginMaximumNoofConcurrentuser", ci));
                                                flag = false;
                                                return;
                                            }
                                            else
                                            {
                                                TimeSpan SessTimeOut = new TimeSpan(0, 0, HttpContext.Current.Session.Timeout, 0, 0);
                                                string userValue = string.Empty;
                                                userValue = Convert.ToString(ipAddress) + "," + loginTime + "," + session_Id;
                                                HttpContext.Current.Cache.Insert(userId.ToUpper(), userValue, null, DateTime.MaxValue, SessTimeOut, System.Web.Caching.CacheItemPriority.NotRemovable, null); // cache handling
                                                Session["cUserName"] = userId.ToUpper();
                                                flag = true;
                                            }
                                        }
                                    }
                                    flag = true; // license information are correct
                                }
                                else
                                    UpdateLicenseMessage();
                            }
                            else
                                UpdateLicenseMessage();
                        }
                    }
                    else
                    {
                        flag = false;
                    }
                    if (flag == true)
                    {
                        DataSet dsLastLogin = new DataSet();
                        dsLastLogin = ObjEmployeeEventData.GetLastLoginTime(Convert.ToString(Session["EmployeeId"]));
                        string strLastLogin = string.Empty;
                        string strLastLogout = string.Empty;
                        if (dsLastLogin.Tables[0].Rows.Count > 0)
                        {
                            if (dsLastLogin.Tables[0].Rows[0]["LastLoginTime"] != DBNull.Value)
                                strLastLogin = Convert.ToString(dsLastLogin.Tables[0].Rows[0]["LastLoginTime"]);
                            if (dsLastLogin.Tables[0].Rows[0]["LastLogoutTime"] != DBNull.Value)
                                strLastLogout = Convert.ToString(dsLastLogin.Tables[0].Rows[0]["LastLogoutTime"]);
                        }
                        Session["LastLoginTime"] = strLastLogin;
                        Session["LastLogoutTime"] = strLastLogout;
                        try
                        {
                            ObjEmployeeEventData.InsertUpdateLastLogin(Convert.ToString(Session["EmployeeId"]));
                        }
                        catch (Exception ex)
                        {
                            Message(ex.ToString());
                        }
                        if (ds_UserName.Tables[0].Rows[0]["UserGroup_Id"] != DBNull.Value)
                        {
                            DataSet dsUserGroup = new DataSet();
                            dsUserGroup = objCommon.SelectGroupName(Convert.ToInt32(ds_UserName.Tables[0].Rows[0]["UserGroup_Id"]));
                            if (dsUserGroup != null)
                            {
                                if (dsUserGroup.Tables.Count > 0)
                                {
                                    if (dsUserGroup.Tables[0].Rows.Count > 0)
                                    {
                                        Session["UserGroupName"] = Convert.ToString(dsUserGroup.Tables[0].Rows[0]["groupName"]);
                                        Session["HasSpecialRights"] = Convert.ToString(dsUserGroup.Tables[0].Rows[0]["hasSpecialRights"]);
                                        Session["ReportsBasedOn"] = Convert.ToString(dsUserGroup.Tables[0].Rows[0]["ReportsBasedOn"]);
                                        Session["IndividualUsers"] = Convert.ToString(dsUserGroup.Tables[0].Rows[0]["IndividualUsers"]);
                                    }
                                }
                            }
                        }
                        Session["ApplnMode"] = "True";
                        if (Request.QueryString["ScheduleId"] != null)
                        {
                            string URL = "Reports/TA_UI_Report_ReportViewer.aspx?" + Convert.ToString(Request.QueryString);
                            Response.Redirect(URL, false);
                        }
                        else
                            RedirectToLandingBasedOnLicense();
                    }
                }
            }
            else
            {
                Session["Edition"] = "0";
                Session["ApplnMode"] = "False";
                String UTC = Convert.ToString(Session["UTCTimeID"]);
                if (Request.QueryString["ScheduleId"] != null)
                {
                    string URL = "Reports/TA_UI_Report_ReportViewer.aspx?" + Convert.ToString(Request.QueryString);
                    Response.Redirect(URL, false);
                }
                else if(UTC == "-Select-")
                {
                    string script = "<script>alert('Select Your TimeZone First Time Log In');</script>";
                    ScriptManager.RegisterStartupScript(this, GetType(), "PopupScript", script, false);

                }
                else
                {
                    Response.Redirect("TA_UI_Valid.aspx");

                }
                    
            }
        }
    }
    private void RedirectToLandingBasedOnLicense()
    {
        switch (Convert.ToString(Session["Edition"]))
        {
            case "1":
            case "2":
                Response.Redirect("Landing.aspx");
                break;
            default:
                if (Convert.ToString(Session["packageID"]) != "")
                {
                    if (Convert.ToInt32(Session["packageID"]) == 168)  //Samsung
                    {
                        Response.Redirect("Dashboard_Samsung.aspx", false);
                        Context.ApplicationInstance.CompleteRequest();
                        //Response.Redirect("Dashboard_Samsung.aspx");
                    }
                    else
                    {
                        if(Session["hdnEmpID"]!="" & Session["HdnReportName"]!=""& Session["HdnFrom"]!=""& Session["HdnTo"]!="" || Session["HdnReport"] !="" || Session["HdnAuthority"] != "")
                        {
                            String EmployeeCode = Session["EmployeeCodeId"].ToString();
                            String HDEMP = Session["hdnEmpID"].ToString();
                            String ReportNo = Session["HdnReport"].ToString();
                            String Authority = Session["HdnAuthority"].ToString();
                            //Session["HdnReport"] = HdnReportNo.Value;
                            //Session["HdnAuthority"] = HdnAuthorityNo.Value; user
                            if (EmployeeCode == HDEMP)
                            {
                                
                                Response.Redirect("Reports/TA_UI_Report_LateInGrid.aspx");

                            }
                            else if(ReportNo != "" || Authority != "")
                            {

                                    if (EmployeeCode == Authority || EmployeeCode == ReportNo)
                                    {
                                        Response.Redirect("Transactions/TA_UI_Transactions_PermissionSanctionModify.aspx");
                                    }
                                    else
                                    {
                                        string strScript;
                                        strScript = "<script language='javascript'>";
                                        strScript = strScript + "alert('" + "Invalid UserName Or Password" + "');";
                                        strScript = strScript + "</script>";
                                        Page.RegisterStartupScript("Alert", strScript);

                                    }

                            }
                            else
                            {
                                string strScript;
                                strScript = "<script language='javascript'>";
                                strScript = strScript + "alert('" + "Invalid UserName Or Password" + "');";
                                strScript = strScript + "</script>";
                                Page.RegisterStartupScript("Alert", strScript);
                            }
                             
                            //Response.Redirect("/Reports/TA_UI_Report_LateInGrid.aspx"); 
                        }
                        else
                        {
                            Response.Redirect("DashBoard.aspx");
                        }
                        
                        
                    }
                }
                else
                {
                    Response.Redirect("DashBoard.aspx");
                }
                break;
        }
    }
    private void UpdateLicenseMessage()
    {
        switch (Convert.ToString(Session["EmployeeId"]).ToLower())
        {
            case "admin":
                MessageWithRedirect(rm.GetString("Alert_PleaseUpdateLicense", ci), "TA_UI_Valid.aspx");
                break;
            default:
                Message(rm.GetString("Alert_ContactAdministrator", ci));
                break;
        }
        flag = false;
    }

    //protected void btnEnter_Click(object sender, EventArgs e)
    //{
    //    String UTC = Convert.ToString( ddlUTCTime.SelectedItem.Value);
    //    Session["UTCTimeID"] = "";
    //    Session["UTCTimeID"] = UTC;

    //    btn_Enter_Click(sender, e);

    //}

    
}