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

public partial class System_Settings_SystemSetting_LicenseUpdater : System.Web.UI.Page
{
    #region VariableDeclaration
    // declaration of required license information variables    
    int MailSendOrNot = 0;
    Cls_CheckUser objCheckUser = new Cls_CheckUser();
    cls_Common objClassCommon = new cls_Common();
    DataSet ds_Checkuser = new DataSet();
    LeaveApplicationEventData objLeaveApplicationEventData = new LeaveApplicationEventData();
    CultureInfo ci;
    ResourceManager rm;
    OL_Services Objservices = new OL_Services();
    // objects creation for Licensing class
    Licensing objLicense = new Licensing();
    DongleAuthentication dongleAuthentication = new DongleAuthentication();
    int master, transaction, report, organizationSetting, systemSetting;
    int dongleId, customerId, softwareId, packageId, noOfConcurrentUser;
    string packageVersion;
    DateTime expiryDate, dateOfIssue;
    string module, module1, module2, module3, module4, module5;
    string strScriptn = string.Empty;
    EmployeeEventData ObjEmployeeEventData = new EmployeeEventData();
    string userId, ipAddress, session_Id;
    #endregion
    #region PageLoad
    protected void Page_Load(object sender, EventArgs e)
    {
        //Call to a function to implement the UserRights
        if (!IsPostBack)
        {
            objClassCommon.menu("LicenseManager", "198");
        }
        UserRights();
        string source_Language;
        source_Language = Convert.ToString(Session["Session_ActiveLanguage"]);
        rm = new ResourceManager(source_Language, System.Reflection.Assembly.Load("App_GlobalResources"));
        ci = Thread.CurrentThread.CurrentCulture;
        site.SiteMapProvider = Convert.ToString(Session["SiteMapProvider"]);
        LoadStrings(ci);
    }
    #endregion
    #region UserDefinedFunctions
    private void LoadStrings(CultureInfo ci)
    {
        lbl_Header.Text = rm.GetString("License_Updater", ci);
        lbl_IndicatesMandatoryFields.Text = rm.GetString("IndicatesMandatoryFields", ci);
        lblLicenseFile.Text = rm.GetString("Select_License_File", ci);
        btnUpload.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Upload", ci);
        btnBack.Text = rm.GetString("btn_Back", ci);
        lblManual.Text = rm.GetString("lblManualUpdation", ci);
        lblOnlineUpdate.Text = rm.GetString("lblOnlineUpdation", ci);
        btnActivation.Text = "&nbsp;&nbsp;" + rm.GetString("lblActivateNow", ci);
    }
    private void UserRights()
    {
        ds_Checkuser = objCheckUser.checkRights(198, Convert.ToInt32(Session["userGroup_Id"]), "addPrv");
        if (ds_Checkuser.Tables[0].Rows.Count == 0)
        {
            Response.Redirect("SystemLandingPage.aspx");
        }
    }
    #endregion
    #region ButtonEvents
    protected void btnBack_Click(object sender, EventArgs e)
    {
        Response.Redirect("System_LicenseManager.aspx");
    }

    
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (fp_ImportFilePath.HasFile)
        {
            string filename = fp_ImportFilePath.FileName;
            string fileType;
            fileType = System.IO.Path.GetExtension(filename);
            bool previousLicenseSE = false;
            if (fileType == ".lic")
            {
                // save uploaded license file
                string strFilePath = Server.MapPath("..\\LicenseFile").ToString();
                fp_ImportFilePath.SaveAs(strFilePath + "\\" + fp_ImportFilePath.FileName);
                System.IO.FileInfo fileInfo = new System.IO.FileInfo(strFilePath + "\\" + fp_ImportFilePath.FileName);
                if (fp_ImportFilePath.PostedFile.ContentLength == fileInfo.Length)
                {
                    // read license key and value to authenticate license
                    string licenseValue = System.Configuration.ConfigurationManager.AppSettings["LicenseKey"].ToString();
                    string licenseFileName = string.Empty;
                    if (licenseValue == "LicenseFile")
                    {
                        // handle soft license(license file)                               
                        licenseFileName = strFilePath + "\\" + fp_ImportFilePath.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();
                        string localMACAdderss = GetMACAddress();
                        // check local and license file MACAddress
                        if (macAddressLicFile != localMACAdderss)
                        {
                            string strScript = "<script language='javascript' type='text/javascript'>";
                            strScript += "alert('" + rm.GetString("Alert_Licensecannotsupportothissystem", ci) + "');";
                            strScript += " </script>";
                            this.RegisterStartupScript("setScript", strScript);
                            return;
                        }
                        else
                        {
                            string[] fileArrDelete;
                            int arrCountDelete = 0;
                            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();
                                                }
                                            }
                                        }
                                        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
                            string emodule = "";
                            string emodule1 = "";
                            string emodule2 = "";
                            string emodule3 = "";
                            string emodule4 = "";
                            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(Convert.ToString(decryptedModuleColumnArr[1]));
                                            drPageInfo["displayName"] =Convert.ToString(decryptedModuleColumnArr[4]);
                                            drPageInfo["path"] = Convert.ToString(decryptedModuleColumnArr[5]);
                                            drPageInfo["parentId"] = Convert.ToInt32(Convert.ToString(decryptedModuleColumnArr[2]));
                                            drPageInfo["orderBy"] = Convert.ToDouble(Convert.ToString(decryptedModuleColumnArr[6]));
                                            if (Convert.ToString(decryptedModuleColumnArr[7]) == string.Empty)
                                            {
                                            }
                                            else
                                            {
                                                drPageInfo["ParentIdForSubMenu"] = Convert.ToDouble(Convert.ToString(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);
                            //Added By A.K.T.MOORTHI(12-May2014)
                            //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"]));
                                }
                            }
                            Base.BasePage objBase = new Base.BasePage();
                            objBase.LogoutUsers();
                            // script for confirmation message
                            string scriptUpdate = "<script language='javascript' type='text/javascript'>";
                            scriptUpdate += "alert('" + rm.GetString("Alert_LicenseInformationupdatedsuccessfully", ci) + "');";
                            scriptUpdate += "location.href='../Index.aspx';";
                            scriptUpdate += " </script>";
                            this.RegisterStartupScript("scriptLicenseUpdate", scriptUpdate);
                        }
                    }
                    else if (licenseValue == "UniKeyDongle")
                    {
                        // handle unikey dongle
                    }
                    else if (licenseValue == "HaspDongle")
                    {
                        // handle hasp dongle
                    }
                }
                else
                {
                    strScriptn = strScriptn + "<script language='javascript'>";
                    strScriptn = strScriptn + "alert('" + rm.GetString("Alert_ErrorinUploading", ci) + "');";
                    strScriptn = strScriptn + "</script>";
                    Page.RegisterStartupScript("Alert", strScriptn);
                }
            }
            else
            {
                strScriptn = strScriptn + "<script language='javascript'>";
                strScriptn = strScriptn + "alert('" + rm.GetString("Alert_Theselectedfileisnotlicensefile", ci) + "');";
                strScriptn = strScriptn + "</script>";
                Page.RegisterStartupScript("Alert", strScriptn);
            }
        }
        else
        {
            strScriptn = strScriptn + "<script language='javascript'>";
            strScriptn = strScriptn + "alert('" + rm.GetString("Alert_Pleasebrowsethelicensefile", ci) + "');";
            strScriptn = strScriptn + "</script> ";
            Page.RegisterStartupScript("Alert", strScriptn);
        }
    }
    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('" + rm.GetString("Alert_Stillyourlicenserequestisnotyetprocessed", ci) + "');", true);
                                }
                            }
                        }
                        else
                        {
                            ScriptManager.RegisterStartupScript(this, GetType(), "Alert", "alert('" + rm.GetString("Alert_Stillyourlicenserequestisnotyetprocessed", ci) + "');", true);
                        }
                    }
                }
            }
        }
        else
        {
            ScriptManager.RegisterStartupScript(this, GetType(), "Alert", "alert('" + rm.GetString("Alert_Internetconnectionwillnotbeavailable", ci) + "');", 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;
    }
    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('" + rm.GetString("Alert_Licensecannotsupportothissystem", ci) + "');";
                strScript += " </script>";
                this.RegisterStartupScript("setScript", strScript);
                //flag = false;
                return;
            }
            else
            {
                //Code added here by prabakaran.p                                    
                string[] fileArrDelete;
                int arrCountDelete = 0;
                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 = objClassCommon.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
                string emodule = "";
                string emodule1 = "";
                string emodule2 = "";
                string emodule3 = "";
                string emodule4 = "";
                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)
                                {
                                }
                                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"]));
                    }
                }
                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);
                }
                // script for confirmation message
                string scriptUpdate = "<script language='javascript' type='text/javascript'>";
                scriptUpdate += "alert('" + rm.GetString("Alert_LicenseInformationupdatedsuccessfully", ci) + "');";
                scriptUpdate += "window.location.href='../index.aspx';";
                scriptUpdate += " </script>";
                this.RegisterStartupScript("scriptLicenseUpdate", scriptUpdate);
            }
        }
        else if (licenseValue == "UniKeyDongle")
        {
            // handle unikey dongle
        }
        else if (licenseValue == "HaspDongle")
        {
            // handle hasp dongle
        }
    }
    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('" + rm.GetString("Alert_Stillyourlicenserequestisnotyetprocessed", ci) + "');", true);
                                }
                            }
                        }
                        else
                        {
                            ScriptManager.RegisterStartupScript(this, GetType(), "Alert", "alert('" + rm.GetString("Alert_Stillyourlicenserequestisnotyetprocessed", ci) + "');", true);
                        }
                    }
                }
            }
        }
        else
        {
            ScriptManager.RegisterStartupScript(this, GetType(), "Alert", "alert('" + rm.GetString("Alert_Internetconnectionwillnotbeavailable", ci) + "');", true);
        }
    }
    #endregion
    private bool CheckDemo()
    {
        string strScript = "";
        string strInstalledDate = "";
        string strExpiryDate = "";
        //Check expiry date      
        CultureInfo provider = CultureInfo.InvariantCulture;
        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.ParseExact(strExpiryDate, "MM/dd/yyyy", provider);
        if (DateTime.Compare(DateTime.Now.Date, dtExpDate) >= 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    /// <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 = cUserCount - 1;
            cUserCount = GetConcurrentUserCount(cUserCount);
        }
        // check concurrent user count
        if (cUserCount == 0)
        {
            // this could be a new "illegal" logon, so we need to check
            // if these credentials are already in the Cache	                                                                                               
            string sUser = Convert.ToString(Cache[userId.ToUpper()]);
            if (sUser == null || sUser == String.Empty)
            {
                // No Cache item, so sesion is either expired or user is new sign-on
                // Set the cache item and Session hit-test for this user---
                TimeSpan SessTimeOut = new TimeSpan(0, 0, HttpContext.Current.Session.Timeout, 0, 0);
                string userValue = string.Empty;
                userValue = 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('" + rm.GetString("Alert_Useriscurrentlyloggedinananothersession", ci) + "');";
                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('" + rm.GetString("Alert_CannotLoginMaximumNoofConcurrentuser", ci) + "');";
                    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 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("<<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);
                }
            }
            // 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("<<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);
                }
            }
            // Send the e-mail message via the specified SMTP server
            client.Send(message);
            MailSendOrNot = 1;
        }
        catch (Exception errorInSendingMail)
        {
            //throw errorInSendingMail;
        }
    }
    #endregion

}