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.Linq;

public partial class GetWindows_Login : 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;
    #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;
    DirectoryEntry myDirectoryEntry = new DirectoryEntry();
    DirectorySearcher mySearcher = new DirectorySearcher();
    SearchResultCollection results;
    string strDomainusername = "";
    string ActiveuserName = string.Empty;
    string ActivePwd = string.Empty;
    string DomainName = string.Empty;
    #endregion
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            CultureInfo cultureInfo = new CultureInfo("en-us");
            cultureInfo.DateTimeFormat.ShortDatePattern = "MM/dd/yyyy";
            System.Threading.Thread.CurrentThread.CurrentCulture = cultureInfo;
            DataSet ds_DateTime = new DataSet();
            #region Checkthedatabaseconnection
            string strDBExists = "0";
            //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;
            }
            #endregion
            ds_DateTime = objshift.Select_DateandTimeFormat();
            if (Convert.ToString(ds_DateTime.Tables[0].Rows[0]["DomainAdminPassword"]) == "")
            {
                Response.Redirect("Index.aspx");
            }
            else
            {
                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["IsDomain"] = Convert.ToString(ds_DateTime.Tables[0].Rows[0]["isDomain"]);
                Session["DomainName"] = Convert.ToString(ds_DateTime.Tables[0].Rows[0]["DomainName"]);
                Session["DomainAdminUserName"] = Convert.ToString(ds_DateTime.Tables[0].Rows[0]["DomainAdminUserName"]);
                Session["DomainAdminPassword"] = Convert.ToString(ds_DateTime.Tables[0].Rows[0]["DomainAdminPassword"]);
                ActiveuserName = Convert.ToString(Session["DomainAdminUserName"]);
                ActivePwd = Encryption.Decrypt(Convert.ToString(Session["DomainAdminPassword"]), "Domain");
                DomainName = Convert.ToString(Session["DomainName"]);
                myDirectoryEntry = new DirectoryEntry("LDAP://" + DomainName, ActiveuserName, ActivePwd);
                mySearcher = new DirectorySearcher(myDirectoryEntry, "(&(SAMAccountName=" + System.Web.HttpContext.Current.Request.LogonUserIdentity.Name.ToString().Split('\\').Last() + ")(objectClass=user)(objectCategory=person))");
                results = mySearcher.FindAll();
                if (results != null)
                {
                    foreach (SearchResult r in results)
                    {
                        if ((r.Properties["mail"].Count > 0 ? r.Properties["mail"][0] : string.Empty).ToString().Length > 5)
                            strDomainusername = (r.Properties["mail"].Count > 0 ? r.Properties["mail"][0] : string.Empty).ToString();
                    }
                    if (strDomainusername == string.Empty)
                    {
                        strDomainusername = System.Web.HttpContext.Current.Request.LogonUserIdentity.Name.ToString().Split('\\').Last();
                        ds_UserName = objCommon.UserAuthenticateDomain(strDomainusername);
                        DomainloginCheckUser();
                    }
                    else
                    {
                        ds_UserName = objCommon.UserAuthenticateDomain(strDomainusername);
                        DomainloginCheckUser();
                    }
                }
                else
                {
                    ds_UserName = objCommon.UserAuthenticateDomain(strDomainusername);
                    DomainloginCheckUser();
                }
            }
        }
        catch(Exception ex)
        {
            
        }
    }
    private void DomainloginCheckUser()
    {
        try
        {
            #region Localvariable
            Session["LastLoginTime"] = string.Empty;
            Session["LastLogoutTime"] = string.Empty;
            Session["ActiveEmployee"] = "5";
            //string strDBExists = "0";
            ////Check the Database connection information is valid
            //string strDecryptedConnectionString = string.Empty;
            DataSet ds_DateTime = new DataSet();
            #endregion
            //#region Checkthedatabaseconnection
            //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;
            //}
            //#endregion
            #region GetTheUserImageBasedOnTheDomainLogin
            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 = 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)
                    {
                        throw ex;
                    }
                }
                else
                {
                    Session["UserImage"] = "emp-photo.png";
                }
            }
            else
            {
                Session["UserImage"] = "emp-photo.png";
            }
            #endregion
            count = ds_UserName.Tables[0].Rows.Count;
            if (count == 1)
            {
                dsLoginLock = ObjEmployeeEventData.GetLockLogin(strDomainusername);
                if (dsLoginLock.Tables[0].Rows.Count <= 0)
                {
                }
                else if (dsLoginLock.Tables[0].Rows.Count > 0)
                {
                    if (Convert.ToString(dsLoginLock.Tables[0].Rows[0]["IsActive"]) == "True")
                    {
                    }
                    else
                    {
                        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));
                        }
                        else
                        {
                            IsActive = 1;
                            ObjEmployeeEventData.InsertUpdateLockLogin(strDomainusername, IsActive);
                        }
                    }
                }
                Session["user"] = UserName;
                Session["EmpAutoID"] = Convert.ToString(ds_UserName.Tables[0].Rows[0]["Employee_Id"]);
                Session["loginEmailId"] = Convert.ToString(ds_UserName.Tables[0].Rows[0]["EmailId"]);
                Session["EmployeeCodeId"] = Convert.ToString(ds_UserName.Tables[0].Rows[0]["Employee_Code_Id"]);
                Session["EmployeeId"] = strDomainusername;
                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";
                DataSet ds = new DataSet();
                DataSet dsChildMenus = new DataSet();
                ds = objCommon.getUserMenu(0, Convert.ToInt16(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;
                    }
                }
                int EmpID;
                EmpID = Convert.ToInt32(Session["EmpAutoID"]);
                //Get Employee Grade Level
                Session["GradeLevel"] = ObjEmployeeEventData.SelectGradeLevel(Convert.ToString(EmpID));
                dsEmployeeLingual = objMultiLingualEventData.GetEmployeeLingual(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"]);
                }
                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);
                    }
                }
                flag = true;
                //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();
                }

                try
                {
                    GetShiftSettingAndLicEmployeeCountDetails();
                }
                catch (Exception ex)
                {

                }

            }
            else
            {
                //Invalid Employees
                return;
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
        }
    }
    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;
            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.ToInt16(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));
                                        }
                                        else
                                        {
                                        }
                                    }
                                }
                                else
                                {
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    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
                {
                    string strScript = "<script language='javascript' type='text/javascript'>";
                    strScript += "alert('" + rm.GetString("Alert_Licenseinformationarenotcorrect", ci) + "');";
                    strScript += " </script>";
                    this.RegisterStartupScript("AlertLicInfoNotCorrect", strScript);
                    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;
                if (packageIdLicFile == "1")
                {
                    Session["Demo"] = "Standard";
                }
                else if (packageIdLicFile == "2")
                {
                    Session["Demo"] = "Express";
                }
                else
                {
                    Session["Demo"] = "Enterprise";
                }
                string packageVersionLicFile = Convert.ToString(basicLicInfoArr[2]);
                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)
                    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;
                                                }
                                                else
                                                {
                                                }
                                            }
                                        }
                                    }
                                    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);
                                    //if (Convert.ToString(localMACAdderss) != "1A153492A74B" && Convert.ToString(localMACAdderss) != "00224DB1924C" && Convert.ToString(localMACAdderss) != "ECA86BFF8FBB")
                                    //{
                                    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);
                                    // commented by Gopinath for online license application
                                    //bool isAllowTerminalAdd = objDemoVersion.LoginCheckTerminalCreation("License", intNoOfTerminalLicFile);
                                    //if (isAllowTerminalAdd)
                                    //{
                                    //    flag = true;
                                    //}
                                    //else
                                    //{
                                    //    Session["sTerminalAllow"] = "0";
                                    //    Response.Redirect("TA_UI_Valid.aspx");
                                    //}
                                    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"])));
                                    // Session["sExpiryDate"] = dtexpiryDateLicFile.ToShortDateString();
                                    if ((span.Days <= 5) && (span.Days >= 0))
                                    {
                                        flag = true;
                                    }
                                    else if (span.Days < 0)
                                    {
                                        //  Response.Redirect("TA_UI_Valid.aspx");
                                        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);
                                    int cUserCount = HttpContext.Current.Cache.Count; // cache handling
                                    string sActiveYearcUserCount = Convert.ToString(Cache["ActiveYearSetting"]);
                                    if (sActiveYearcUserCount == null || sActiveYearcUserCount == String.Empty)
                                    {
                                    }
                                    else
                                    {
                                        cUserCount = cUserCount - 1;
                                    }
                                    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;
                                    //        concurrentUserCount = HttpContext.Current.Cache.Count;
                                    //        string sActiveYear = Convert.ToString(Cache["ActiveYearSetting"]);
                                    //        if (sActiveYear == null || sActiveYear == String.Empty)
                                    //        {
                                    //        }
                                    //        else
                                    //        {
                                    //            concurrentUserCount = concurrentUserCount - 1;
                                    //        }
                                    //        if (userId.ToLower() != "admin" && concurrentUserCount >= Convert.ToInt32(noOfConcurrentUserLicFile))
                                    //        {
                                    //            licenseUptScript = "<script language='javascript' type='text/javascript'>";
                                    //            licenseUptScript += "alert('" + rm.GetString("Alert_CannotLogin", ci) + "');";
                                    //            licenseUptScript += " </script>";
                                    //            this.RegisterStartupScript("licenseUptScript6", licenseUptScript);
                                    //            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
                                {
                                    if (Convert.ToString(Session["EmployeeId"]).ToLower() == "admin")
                                    {
                                        licenseUptScript = "<script language='javascript' type='text/javascript'>";
                                        licenseUptScript += "alert('" + rm.GetString("Alert_PleaseUpdateLicense", ci) + "');";
                                        licenseUptScript += "location.href='TA_UI_Valid.aspx';";
                                        licenseUptScript += " </script>";
                                        this.RegisterStartupScript("licenseUptScript1", licenseUptScript);
                                        flag = false;
                                    }
                                    else
                                    {
                                        licenseUptScript = "<script language='javascript' type='text/javascript'>";
                                        licenseUptScript += "alert('" + rm.GetString("Alert_ContactAdministrator", ci) + "');";
                                        licenseUptScript += " </script>";
                                        this.RegisterStartupScript("licenseUptScript2", licenseUptScript);
                                        flag = false;
                                    }
                                }
                            }
                            else
                            {
                                if (Convert.ToString(Session["EmployeeId"]).ToLower() == "admin")
                                {
                                    licenseUptScript = "<script language='javascript' type='text/javascript'>";
                                    licenseUptScript += "alert('" + rm.GetString("Alert_PleaseUpdateLicense", ci) + "');";
                                    licenseUptScript += "location.href='TA_UI_Valid.aspx';";
                                    licenseUptScript += " </script>";
                                    this.RegisterStartupScript("licenseUptScript3", licenseUptScript);
                                    flag = false;
                                }
                                else
                                {
                                    licenseUptScript = "<script language='javascript' type='text/javascript'>";
                                    licenseUptScript += "alert('" + rm.GetString("Alert_ContactAdministrator", ci) + "');";
                                    licenseUptScript += " </script>";
                                    this.RegisterStartupScript("licenseUptScript4", licenseUptScript);
                                    flag = false;
                                }
                            }
                        }
                    }
                    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)
                        {
                            Response.Write(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
                        {
                            if (Convert.ToString(Session["Edition"]) == "1" || Convert.ToString(Session["Edition"]) == "2")
                            {
                                Response.Redirect("Landing.aspx");
                            }
                            else
                            {
                                Response.Redirect("DashBoard.aspx");
                                //Response.Redirect("Landing.aspx");
                            }
                        }
                    }
                }
            }
            else
            {
                Session["Edition"] = "0";
                Session["ApplnMode"] = "False";
                if (Request.QueryString["ScheduleId"] != null)
                {
                    string URL = "Reports/TA_UI_Report_ReportViewer.aspx?" + Convert.ToString(Request.QueryString);
                    Response.Redirect(URL, false);
                }
                else
                {
                    Response.Redirect("TA_UI_Valid.aspx");
                }
                //Response.Redirect("TA_UI_Valid.aspx");
            }
        }
        else if (licenseValue == "UniKeyDongle")
        {
        }
        else if (licenseValue == "HaspDongle")
        {
        }
    }
    #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
    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
            {
                if (Convert.ToString(Session["Edition"]) == "1" || Convert.ToString(Session["Edition"]) == "2")
                {
                    Response.Redirect("Landing.aspx");
                }
                else
                {
                    Response.Redirect("DashBoard.aspx");
                    //Response.Redirect("Landing.aspx");
                }
            }
        }
    }
    #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)
            {
                //string strScript = "<script language='javascript' type='text/javascript'>";
                //strScript += "alert('License cannot support to this system');";
                //strScript += " </script>";
                //this.RegisterStartupScript("setScript", strScript);
                //flag = false;
                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)
                                    {
                                        Response.Write(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"]);
                                            }
                                        }
                                    }
                                    string strScript = "<script language='javascript' type='text/javascript'>";
                                    strScript += "alert('" + strStatus + "');";
                                    strScript += "location.href='Landing.aspx';";
                                    strScript += " </script>";
                                    this.RegisterStartupScript("setScript", strScript);
                                    return;
                                }
                                else
                                {
                                    return;
                                }
                            }
                            else
                            {
                                string strScript = "<script language='javascript' type='text/javascript'>";
                                strScript += "alert('" + strStatus + "');";
                                strScript += " </script>";
                                this.RegisterStartupScript("setScript", strScript);
                                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)
                                {
                                    //drPageInfo["ParentIdForSubMenu"] = Convert.ToDouble(decryptedModuleColumnArr[7].ToString());
                                }
                                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"]));
                    }
                    else
                    {
                        // nothing
                    }
                }
                Base.BasePage objBase = new Base.BasePage();
                objBase.LogoutUsers();
                //MailSendOrNot = 1;
                //if (MailSendOrNot == 1)
                //{
                //    TriggerMail("Dear Admin,<br /><br />License was activated by " + CustomerName + " sucessfully.<br /> Kindly find the configuration details below<br />", "Timecheck - License Activation", ToMailID, CCmailID, noOfEmployee, noOfConcurrentUser, noOfTerminal, CustomerName, VersionType);
                //    TriggerMailCustomer("Dear " + CustomerName + ",<br /><br />License was activated sucessfully.<br /> Kindly find the configuration details below<br />", "Timecheck - License Activation", EmployeeEmail, noOfEmployee, noOfConcurrentUser, noOfTerminal, CustomerName, VersionType);
                //}
                // script for confirmation message
                //string scriptUpdate = "<script language='javascript' type='text/javascript'>";
                //scriptUpdate += "alert('License Information has been updated successfully!');";
                //scriptUpdate += "location.replace('index.aspx');";
                //scriptUpdate += " </script>";
                //this.RegisterStartupScript("scriptLicenseUpdate", scriptUpdate);
            }
        }
        else if (licenseValue == "UniKeyDongle")
        {
            // handle unikey dongle
        }
        else if (licenseValue == "HaspDongle")
        {
            // handle hasp dongle
        }
    }
    #endregion
    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);
        int cUserCount = HttpContext.Current.Cache.Count; // cache handling
        string sActiveYearcUserCount = Convert.ToString(Cache["ActiveYearSetting"]);
        if (sActiveYearcUserCount == null || sActiveYearcUserCount == String.Empty)
        {
        }
        else
        {
            cUserCount = cUserCount - 1;
        }
        // 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)
            {
                licenseUptScript = "<script language='javascript' type='text/javascript'>";
                licenseUptScript += "alert('User is currently logged in an another session. If you want kill that session Press Proceed!');";
                licenseUptScript += " </script>";
                this.RegisterStartupScript("licenseUptScript6", licenseUptScript);
                return false;
            }
            else
            {
                // check count of concurrent user      
                // for concurrent user not more than 3
                // int concurrentUserCount = objCommon.CheckConcurrentUserCount();
                int concurrentUserCount = 0;
                concurrentUserCount = HttpContext.Current.Cache.Count;
                string sActiveYear = Convert.ToString(Cache["ActiveYearSetting"]);
                if (sActiveYear == null || sActiveYear == String.Empty)
                {
                }
                else
                {
                    concurrentUserCount = concurrentUserCount - 1;
                }
                if (userId.ToLower() != "admin" && concurrentUserCount >= 3)
                {
                    licenseUptScript = "<script language='javascript' type='text/javascript'>";
                    licenseUptScript += "alert('Cannot Login, Maximum No. of Concurrent user count is reached!');";
                    licenseUptScript += "location.href='index.aspx';";
                    licenseUptScript += " </script>";
                    this.RegisterStartupScript("licenseUptScript6", licenseUptScript);
                    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;
    }
    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;
    }
   
}