using System;
using System.Configuration;
using System.Data;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Web;
using System.Web.UI;
using OLServices;
using Cryptographys;
using System.Net.NetworkInformation;
using System.Collections;

public partial class License_Activation : System.Web.UI.Page
{
    #region Variable Declarion
    int MailSendOrNot = 0;
    Licensing objLicense = new Licensing();
    OL_Services Objservices = new OL_Services();
    cls_Common objClassCommon = new cls_Common();
    DongleAuthentication dongleAuthentication = new DongleAuthentication();
    EmployeeEventData ObjEmployeeEventData = new EmployeeEventData();
    cls_Common objCommon = new cls_Common();
    // 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;
    LeaveApplicationEventData objLeaveApplicationEventData = new LeaveApplicationEventData();
    // for module information
    string module, module1, module2, module3, module4, module5;
    string strScriptn = string.Empty;
    string userId, ipAddress, session_Id, res, db_sessionId;
    #endregion
    #region PageLoad
    protected void Page_Load(object sender, EventArgs e)
    {
        // objects creation for Licensing class
        DataSet dsLicenseInfo = new DataSet();
        string localMACAdderss = GetMACAddress();
        localMACAdderss = Encryption.Encrypt(localMACAdderss, "");
        dsLicenseInfo = objLicense.SelectFromProtectionTable(localMACAdderss);
        if (dsLicenseInfo != null)
        {
            if (dsLicenseInfo.Tables.Count > 0)
            {
                if (dsLicenseInfo.Tables[0].Rows.Count == 0)
                {
                    DataSet dsResponse = new DataSet();
                    dsResponse = objLicense.GettingResponseStatus();
                    if (dsResponse != null)
                    {
                        if (dsResponse.Tables.Count > 0)
                        {
                            if (dsResponse.Tables[0].Rows.Count > 0)
                            {
                                trReActive.Visible = false;
                                btnActivation.Enabled = true;
                            }
                            else
                            {
                                trReActive.Visible = false;
                                btnActivation.Enabled = false;
                            }
                        }
                    }
                }
                else
                {
                    //license already purchased but requested for renewal
                    DataSet dsResponse = new DataSet();
                    dsResponse = objLicense.GettingResponseStatus();
                    if (dsResponse != null)
                    {
                        if (dsResponse.Tables.Count > 0)
                        {
                            trActive.Visible = false;
                            btnReactivation.Enabled = true;
                        }
                    }
                }
            }
        }
    }
    #endregion
    #region Button Click Events
    protected void btnback_Click(object sender, EventArgs e)
    {
        Response.Redirect("TA_UI_Valid.aspx");
    }
    protected void btnActivation_Click(object sender, EventArgs e)
    {
        bool NetResult = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
        if (NetResult == true)
        {
            Int64 RequestID = 0;
            DataSet dsCheckRequestID = new DataSet();
            dsCheckRequestID = objLicense.SelectLicenseRequestID();
            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 = Server.MapPath("~\\LicenseFile").ToString();
                                    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
                                {
                                    ScriptManager.RegisterStartupScript(this, GetType(), "Alert", "alert('Still your license request is not yet processed');", true);
                                }
                            }
                        }
                        else
                        {
                            ScriptManager.RegisterStartupScript(this, GetType(), "Alert", "alert('Still your license request is not yet processed');", true);
                        }
                    }
                }
            }
        }
        else
        {
            ScriptManager.RegisterStartupScript(this, GetType(), "Alert", "alert('Internet connection will not be available.Kindly check it.');", true);
        }
    }
    protected void btnReactivation_Click(object sender, EventArgs e)
    {
        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 = Server.MapPath("~\\LicenseFile").ToString();
                                    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
                                {
                                    ScriptManager.RegisterStartupScript(this, GetType(), "Alert", "alert('Still your license request is not yet processed');", true);
                                }
                            }
                        }
                        else
                        {
                            ScriptManager.RegisterStartupScript(this, GetType(), "Alert", "alert('Still your license request is not yet processed');", true);
                        }
                    }
                }
            }
        }
        else
        {
            ScriptManager.RegisterStartupScript(this, GetType(), "Alert", "alert('Internet connection will not be available.Kindly check it.');", true);
        }
    }
    #endregion
    #region User Defiened Functions
    private void CreateLicenseFile(string licenseFilePath, string licenseInfoEncrypted)
    {
        try
        {
            //File Stream pointing to License File,if exist or creates a License file
            FileStream licenseFileStream = new FileStream(licenseFilePath, FileMode.OpenOrCreate);
            //Stream Writer pointing to License  File
            StreamWriter licenseStreamWriter = new StreamWriter(licenseFileStream);
            //Encrypted string is written into the License File.
            licenseStreamWriter.WriteLine(licenseInfoEncrypted);
            //Closes the Streams
            licenseStreamWriter.Close();
            licenseFileStream.Close();
            // A message is displayed to the user indicating LicenseFile is created.                
            //MessageBox.Show(this, "License file has been created in the following path: " + licenseFilePath, "Alert", MessageBoxButtons.OK, MessageBoxIcon.Information);
            // lblFolderPath.Text = "Folder Path";
        }
        catch (Exception ex)
        {
            //A error message is displayed.
            //s   MessageBox.Show(ex.Message);
        }
    }

    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;
    }
    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 = Server.MapPath("~\\LicenseFile").ToString();
        System.IO.FileInfo fileInfo = new System.IO.FileInfo(strFilePath + "\\" + filename);
        // read license key and value to authenticate license
        string licenseValue = System.Configuration.ConfigurationManager.AppSettings["LicenseKey"].ToString();
        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 = decryptedLicFileInfoArr[0].ToString();
            string[] basicLicInfoArr = basicLicInfo.Split(',');
            // set license file MACAddress
            string macAddressLicFile = basicLicInfoArr[5].ToString();
            // get local MACAddress
            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 (basicLicInfoArr[1].ToString() == "1")
                {
                    DataSet dsPendingForwarded = new DataSet();
                    dsPendingForwarded = objLicense.SelectLICPendingForwardedRecords();
                    if (dsPendingForwarded.Tables[0].Rows.Count > 0)
                    {
                        string strStatus = string.Empty;
                        strStatus = dsPendingForwarded.Tables[0].Rows[0]["Result"].ToString();
                        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 = fileArrDelete[i].ToString();
                                    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 = dsLastLogin.Tables[0].Rows[0]["LastLoginTime"].ToString();
                                        }
                                        if (dsLastLogin.Tables[0].Rows[0]["LastLogoutTime"] != DBNull.Value)
                                        {
                                            strLastLogout = dsLastLogin.Tables[0].Rows[0]["LastLogoutTime"].ToString();
                                        }
                                    }
                                    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 = fileArrDelete[i].ToString();
                        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 = basicLicInfoArr[0].ToString();
                string ecustomerId = Encryption.Encrypt(customerId, "");
                packageId = basicLicInfoArr[1].ToString();
                string epackageId = Encryption.Encrypt(packageId, "");
                packageVersion = basicLicInfoArr[2].ToString();
                string epackageVersion = Encryption.Encrypt(packageVersion, "");
                noOfConcurrentUser = basicLicInfoArr[3].ToString();
                string enoOfConcurrentUser = Encryption.Encrypt(noOfConcurrentUser, "");
                noOfEmployee = basicLicInfoArr[4].ToString();
                string enoOfEmployee = Encryption.Encrypt(noOfEmployee, "");
                string emacAddressLicFile = Encryption.Encrypt(macAddressLicFile, "");
                licenseGenerationDate = basicLicInfoArr[6].ToString();
                string elicenseGenerationDate = Encryption.Encrypt(licenseGenerationDate, "");
                expiryDate = basicLicInfoArr[7].ToString();
                string eexpiryDate = Encryption.Encrypt(expiryDate, "");
                noOfTerminal = basicLicInfoArr[8].ToString();
                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 = decryptedLicFileInfoArr[i].ToString();
                        string[] decryptedModuleArr = moduleInfo.Split('*');
                        for (int j = 0; j < decryptedModuleArr.Length; j++)
                        {
                            string[] decryptedModuleColumnArr = decryptedModuleArr[j].ToString().Split(',');
                            if (decryptedModuleColumnArr[3].ToString() == "1")
                            {
                                drPageInfo = dtPageInfo.NewRow();
                                drPageInfo.BeginEdit();
                                drPageInfo["pageId"] = Convert.ToDouble(decryptedModuleColumnArr[1].ToString());
                                drPageInfo["displayName"] = decryptedModuleColumnArr[4].ToString();
                                drPageInfo["path"] = decryptedModuleColumnArr[5].ToString();
                                drPageInfo["parentId"] = Convert.ToInt32(decryptedModuleColumnArr[2].ToString());
                                drPageInfo["orderBy"] = Convert.ToDouble(decryptedModuleColumnArr[6].ToString());
                                if (decryptedModuleColumnArr[7].ToString() == string.Empty)
                                {
                                    //drPageInfo["ParentIdForSubMenu"] = Convert.ToDouble(decryptedModuleColumnArr[7].ToString());
                                }
                                else
                                {
                                    drPageInfo["ParentIdForSubMenu"] = Convert.ToDouble(decryptedModuleColumnArr[7].ToString());
                                }
                                drPageInfo.EndEdit();
                                dtPageInfo.Rows.Add(drPageInfo);
                                if (decryptedModuleColumnArr[2].ToString() != "0")
                                {
                                    // collect the page ids in string to insert relevant user rights data                                 
                                    if (enterprisePageIds == string.Empty)
                                    {
                                        enterprisePageIds = decryptedModuleColumnArr[1].ToString();
                                        parenIds = decryptedModuleColumnArr[2].ToString();
                                    }
                                    else
                                    {
                                        enterprisePageIds = enterprisePageIds + "," + decryptedModuleColumnArr[1].ToString();
                                        parenIds = parenIds + "," + decryptedModuleColumnArr[2].ToString();
                                    }
                                }
                            }
                            else
                            {
                                // collect the page ids in string to delete relevant user rights data                                 
                                if (pageStatusFalse == string.Empty)
                                {
                                    pageStatusFalse = decryptedModuleColumnArr[1].ToString();
                                }
                                else
                                {
                                    pageStatusFalse = pageStatusFalse + "," + decryptedModuleColumnArr[1].ToString();
                                }
                            }
                        }
                    }
                }
                // 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);
                //Created By A.K.T.MOORTHI(12-May2014), Added by gopinath for bug no.27711
                //Activate The Licence Employee Based On No Employee From Licence File
                objLicense.ActivateEmployeeBasedOnLicence(noOfEmployee);
                objLicense.UpdateUserRightsDetails();
                // 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 = objClassCommon.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 (Convert.ToInt32(ConfigurationManager.AppSettings.Get("isRequiredEmail")) == 1)
                {
                    TriggerMail("<b>Dear Admin</b>,<br /><br /><font face='Verdana' color='#000' size='2'>License was activated by " + CustomerName + " sucessfully.<br /> Kindly find the configuration details below<br /></font>", "Timecheck - License Activation", ToMailID, CCmailID, noOfEmployee, noOfConcurrentUser, noOfTerminal, CustomerName, VersionType);
                    TriggerMailCustomer("<b>Dear " + CustomerName + "</b>,<br /><br /><font face='Verdana' color='#000' size='2'>License was activated sucessfully.<br /> Kindly find the configuration details below<br /></font>", "Timecheck - License Activation", EmployeeEmail, noOfEmployee, noOfConcurrentUser, noOfTerminal, CustomerName, VersionType);
                    //   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
        }
    }
    private bool CheckDemo()
    {
        string strScript = "";
        string strInstalledDate = "";
        string strExpiryDate = "";
        //Check expiry date       
        strInstalledDate = System.Configuration.ConfigurationManager.AppSettings["Validate1"].ToString();
        strExpiryDate = System.Configuration.ConfigurationManager.AppSettings["Validate2"].ToString();
        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;
        }
    }
    //End of Expiry date    
    /// <summary>
    /// Get the Concurrent User Count details.
    /// </summary>
    /// <param name="concurrentUserCount"></param>
    /// <returns></returns>
    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;
    }
    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 = Request.ServerVariables["REMOTE_ADDR"].ToString();
        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 = Session.SessionID.ToString();
        //Due to cache,its showing wrong count of concurrent user.
        //so we commented below line on 14-Feb-2020 13:30 PM
        //int cUserCount = HttpContext.Current.Cache.Count; // cache handling
        int cUserCount = 0;
        string sActiveYearcUserCount = Convert.ToString(Cache["ActiveYearSetting"]);
        if (sActiveYearcUserCount == null || sActiveYearcUserCount == String.Empty)
        {
        }
        else
        {
            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 = ipAddress.ToString() + "," + 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;
                //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 = concurrentUserCount - 1;
                    concurrentUserCount = GetConcurrentUserCount(concurrentUserCount);
                }
                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 = ipAddress.ToString() + "," + 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;
    }
    #region EmailTriggering
    //public void TriggerMail(string bodyContent, string subject, string ToEmail, string CcEmail,string noOfEmployee,string noOfConcurrentUser,string noOfTerminal)
    //{
    //    string FromEmailId = string.Empty;
    //    string SMTPHost = string.Empty;
    //    string SMTPPort = string.Empty;
    //    string NetUserName = string.Empty;
    //    string NetPassword = string.Empty;
    //    MailMessage message = new MailMessage();
    //    try
    //    {
    //        FromEmailId = Convert.ToString(ConfigurationManager.AppSettings["FromId"]);
    //        SMTPHost = Convert.ToString(ConfigurationManager.AppSettings["SMTPClientHost"]);
    //        SMTPPort = Convert.ToString(ConfigurationManager.AppSettings["SMTPPort"]);
    //        NetUserName = Convert.ToString(ConfigurationManager.AppSettings["MailAuthenticateUser"]);
    //        NetPassword = Convert.ToString(ConfigurationManager.AppSettings["MailAuthenticatePassword"]);
    //        NetworkCredential crdntl = new NetworkCredential();
    //        SmtpClient client = new SmtpClient(SMTPHost, Convert.ToInt32(SMTPPort));
    //        string Body = "";
    //        Body = Body + "<html><body><table width='750px' style='border: solid 1px black;' cellspacing='0' cellpadding='0'><tr><td style='width:100%;background-color:#d3dbe7;'><img src='cid:image1' style='float:left;padding-left:10px;border:none;'><a href='http://www.angleritech.com' target='_blank'><img src='cid:imgCompLogo' style='float: right; padding-right: 10px; padding-top: 10px;border: none;' /></a></td></tr><br>";
    //        Body = Body + "<tr><td style='width:100%;background-color: #E0E6EE;'>" + bodyContent + "<br><br></td></tr>";
    //        Body = Body + "<tr><td style='width:100%;background-color:#d3dbe7;text-align: right;'><a href='http://angeritech.com' target='_blank' style='text-decoration: none; color: #224d6a;'> Angler Technologies </a></td></tr></table></body></html>" + Environment.NewLine;
    //       // Body = Body + "<html><body><table width='750px' style='background-color:#F4F4F4;'><tr><td style='width:100%;background-color:#d3dbe7;'><img src='cid:image1' style='float:left;padding-left:10px;border:none;'><a href='http://www.angleritech.com' target='_blank'><img src='cid:imgCompLogo' style='float: right; padding-right: 10px; padding-top: 10px;border: none;' /></a></td></tr><br>";
    //       // Body = Body + "<tr><td style='width:100%;'>" + bodyContent + "<br></td></tr>";
    //       // Body = Body + "<tr><td style='width:100%;background-color:#d3dbe7;text-align: right;'><a href='http://angeritech.com' target='_blank' style='text-decoration: none; color: #224d6a;'> Angler Technologies </a></td></tr></table></body></html>" + Environment.NewLine;
    //        message.Body = Body;
    //        message.IsBodyHtml = true;
    //        message.Subject = subject;
    //        message.From = new MailAddress(FromEmailId);
    //        AlternateView htmlview = default(AlternateView);
    //        htmlview = AlternateView.CreateAlternateViewFromString(message.Body, null, "text/html");
    //        LinkedResource imageResourceEs = new LinkedResource(Server.MapPath("~/images/" + "logo.png"), "image/png");
    //        imageResourceEs.ContentId = "image1";
    //        imageResourceEs.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
    //        htmlview.LinkedResources.Add(imageResourceEs);
    //        LinkedResource imgCompLogo = new LinkedResource(Server.MapPath("~/images/" + "AngLogoNew.png"), "image/png");
    //        imgCompLogo.ContentId = "imgCompLogo";
    //        imgCompLogo.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
    //        htmlview.LinkedResources.Add(imgCompLogo);
    //        message.AlternateViews.Add(htmlview);
    //        char[] split = { ';' };
    //        string[] strToEmailIds = ToEmail.Split(split);
    //        foreach (string strToMail in strToEmailIds)
    //        {
    //            if (strToMail != string.Empty)
    //            {
    //                message.To.Add(strToMail);
    //            }
    //        }
    //        string[] strCcEmailIds = CcEmail.Split(split);
    //        foreach (string strCcMail in strCcEmailIds)
    //        {
    //            if (strCcMail != string.Empty)
    //            {
    //                message.CC.Add(strCcMail);
    //            }
    //        }
    //        //ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
    //        // Send the e-mail message via the specified SMTP server
    //        client.Send(message);
    //        MailSendOrNot = 1;
    //    }
    //    catch (Exception errorInSendingMail)
    //    {
    //        //throw errorInSendingMail;
    //    }
    //}
    public void TriggerMail(string bodyContent, string subject, string ToEmail, string CcEmail, string noOfEmployee, string noOfConcurrentUser, string noOfTerminal, string CustomerName, string packageVersion)
    {
        string scriptText;
        string FromEmailId = string.Empty;
        string SMTPHost = string.Empty;
        string SMTPPort = string.Empty;
        string NetUserName = string.Empty;
        string NetPassword = string.Empty;
        DataTable dtTableScript = new DataTable();
        MailMessage message = new MailMessage();
        MailMessage Clientmessage = new MailMessage();
        try
        {
            string ScriptType = "License Activation";
            dtTableScript = objLeaveApplicationEventData.GetEmailScripts(ScriptType);
            scriptText = dtTableScript.Rows[0]["ScriptText"].ToString();
            FromEmailId = Convert.ToString(ConfigurationManager.AppSettings["FromId"]);
            SMTPHost = Convert.ToString(ConfigurationManager.AppSettings["SMTPClientHost"]);
            SMTPPort = Convert.ToString(ConfigurationManager.AppSettings["SMTPPort"]);
            NetUserName = Convert.ToString(ConfigurationManager.AppSettings["MailAuthenticateUser"]);
            NetPassword = Convert.ToString(ConfigurationManager.AppSettings["MailAuthenticatePassword"]);
            NetworkCredential crdntl = new NetworkCredential();
            SmtpClient client = new SmtpClient(SMTPHost, Convert.ToInt32(SMTPPort));
            message.IsBodyHtml = true;
            message.Subject = subject;
            // message.Body = scriptText.Replace("<<licenserequestUsername>>", " ");
            message.Body = scriptText.Replace("<<licenserequestdetails>>", bodyContent);
            message.Body = message.Body.Replace("<<lblemployee>>", "Number Of Employees");
            message.Body = message.Body.Replace("<<employee>>", noOfEmployee);
            message.Body = message.Body.Replace("<<lblconcurrentusers>>", "Number Of Concurrent Users");
            message.Body = message.Body.Replace("<<concurrentusers>>", noOfConcurrentUser);
            message.Body = message.Body.Replace("<<lblterminals>>", "Number Of Terminals");
            message.Body = message.Body.Replace("<<terminals>>", noOfTerminal);
            message.Body = message.Body.Replace("<<lblversion>>", "Version Type");
            message.Body = message.Body.Replace("<<version>>", packageVersion);
            message.Body = message.Body.Replace("<<regards>>", "Regards,");
            message.Body = message.Body.Replace("<<clientname>>", CustomerName);
            message.From = new MailAddress(FromEmailId);
            AlternateView htmlview = default(AlternateView);
            htmlview = AlternateView.CreateAlternateViewFromString(message.Body, null, "text/html");
            LinkedResource imageResourceEs = new LinkedResource(Server.MapPath("~/images/" + "logo.png"), "image/png");
            imageResourceEs.ContentId = "image1";
            imageResourceEs.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
            htmlview.LinkedResources.Add(imageResourceEs);
            LinkedResource imgCompLogo = new LinkedResource(Server.MapPath("~/images/" + "AngLogoNew.png"), "image/png");
            imgCompLogo.ContentId = "imgCompLogo";
            imgCompLogo.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
            htmlview.LinkedResources.Add(imgCompLogo);
            message.AlternateViews.Add(htmlview);
            char[] split = { ';' };
            string[] strToEmailIds = ToEmail.Split(split);
            foreach (string strToMail in strToEmailIds)
            {
                if (strToMail != string.Empty)
                {
                    message.To.Add(strToMail);
                }
            }
            string[] strCcEmailIds = CcEmail.Split(split);
            foreach (string strCcMail in strCcEmailIds)
            {
                if (strCcMail != string.Empty)
                {
                    message.CC.Add(strCcMail);
                }
            }
            //ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
            // Send the e-mail message via the specified SMTP server
            client.Send(message);
            MailSendOrNot = 1;
        }
        catch (Exception errorInSendingMail)
        {
            //throw errorInSendingMail;
        }
    }
    public void TriggerMailCustomer(string bodyContent, string subject, string ToEmail, string noOfEmployee, string noOfConcurrentUser, string noOfTerminal, string CustomerName, string packageVersion)
    {
        string scriptText;
        string FromEmailId = string.Empty;
        string SMTPHost = string.Empty;
        string SMTPPort = string.Empty;
        string NetUserName = string.Empty;
        string NetPassword = string.Empty;
        DataTable dtTableScript = new DataTable();
        MailMessage message = new MailMessage();
        MailMessage Clientmessage = new MailMessage();
        try
        {
            string ScriptType = "License Activation";
            dtTableScript = objLeaveApplicationEventData.GetEmailScripts(ScriptType);
            scriptText = dtTableScript.Rows[0]["ScriptText"].ToString();
            FromEmailId = Convert.ToString(ConfigurationManager.AppSettings["FromId"]);
            SMTPHost = Convert.ToString(ConfigurationManager.AppSettings["SMTPClientHost"]);
            SMTPPort = Convert.ToString(ConfigurationManager.AppSettings["SMTPPort"]);
            NetUserName = Convert.ToString(ConfigurationManager.AppSettings["MailAuthenticateUser"]);
            NetPassword = Convert.ToString(ConfigurationManager.AppSettings["MailAuthenticatePassword"]);
            NetworkCredential crdntl = new NetworkCredential();
            SmtpClient client = new SmtpClient(SMTPHost, Convert.ToInt32(SMTPPort));
            message.IsBodyHtml = true;
            message.Subject = subject;
            // message.Body = scriptText.Replace("<<licenserequestUsername>>","");
            message.Body = scriptText.Replace("<<licenserequestdetails>>", bodyContent);
            message.Body = message.Body.Replace("<<lblemployee>>", "Number Of Employees");
            message.Body = message.Body.Replace("<<employee>>", noOfEmployee);
            message.Body = message.Body.Replace("<<lblconcurrentusers>>", "Number Of Concurrent Users");
            message.Body = message.Body.Replace("<<concurrentusers>>", noOfConcurrentUser);
            message.Body = message.Body.Replace("<<lblterminals>>", "Number Of Terminals");
            message.Body = message.Body.Replace("<<terminals>>", noOfTerminal);
            message.Body = message.Body.Replace("<<lblversion>>", "Version Type");
            message.Body = message.Body.Replace("<<version>>", packageVersion);
            message.Body = message.Body.Replace("<<regards>>", "Regards,");
            message.Body = message.Body.Replace("<<clientname>>", "TimeCheck");
            message.From = new MailAddress(FromEmailId);
            AlternateView htmlview = default(AlternateView);
            htmlview = AlternateView.CreateAlternateViewFromString(message.Body, null, "text/html");
            LinkedResource imageResourceEs = new LinkedResource(Server.MapPath("~/images/" + "logo.png"), "image/png");
            imageResourceEs.ContentId = "image1";
            imageResourceEs.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
            htmlview.LinkedResources.Add(imageResourceEs);
            LinkedResource imgCompLogo = new LinkedResource(Server.MapPath("~/images/" + "AngLogoNew.png"), "image/png");
            imgCompLogo.ContentId = "imgCompLogo";
            imgCompLogo.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
            htmlview.LinkedResources.Add(imgCompLogo);
            message.AlternateViews.Add(htmlview);
            char[] split = { ';' };
            string[] strToEmailIds = ToEmail.Split(split);
            foreach (string strToMail in strToEmailIds)
            {
                if (strToMail != string.Empty)
                {
                    message.To.Add(strToMail);
                }
            }
            //string[] strCcEmailIds = CcEmail.Split(split);
            //foreach (string strCcMail in strCcEmailIds)
            //{
            //    if (strCcMail != string.Empty)
            //    {
            //        message.CC.Add(strCcMail);
            //    }
            //}
            //ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
            // Send the e-mail message via the specified SMTP server
            client.Send(message);
            MailSendOrNot = 1;
        }
        catch (Exception errorInSendingMail)
        {
            //throw errorInSendingMail;
        }
    }
    #endregion
    #endregion
}
