using System;
using System.IO;
using System.Security.Principal;
using System.Text;
using System.Web.Configuration;
using System.Xml;
using System.ServiceProcess;
using Cryptographys;
public partial class TA_UI_Database_Configuration : Base.BasePage
{
    cls_Common objCommon = new cls_Common();
    StringBuilder sbConnection = new StringBuilder();
    StringBuilder sbDataProcessConnection = new StringBuilder();
    string gstrServerName = string.Empty;
    string gstrEncryptedKey = string.Empty;
    string strRawDataFileName = string.Empty;
    string strRawDataFileType = string.Empty;
    bool blnRawDataExists = false;
    string strDataProcessFileName = string.Empty;
    string strDataProcessFileType = string.Empty;
    //Email Schedular File Path & Type getting here by Manjula.P on 18-Mar-2015
    string strEmailSchedularFileName = string.Empty;
    string strEmailSchedularFileType = string.Empty;
    bool blnEmailSchedularExists = false;
    //End Of Email Schedular File Path & Type getting here by Manjula.P on 18-Mar-2015
    bool blnDataProcessExists = false;
    string strDBExists = "0";
    int intSuperAdminUser = 0;
    string strDelarLogo;
    protected override void Page_Load(object sender, EventArgs e)
    {
        GetImagePath();
        gstrEncryptedKey = "TimecheckPhaseI";
        if (!IsPostBack)
        {
            string strDBExists = "0";
            string strDecryptedConnectionString = string.Empty;
            strDecryptedConnectionString = Cryptographys.Cryptography.GetDecryptedConnectionString();
            strDBExists = objCommon.CheckDatabaseExists(strDecryptedConnectionString);
            if (strDBExists == "1")
            {
                Response.Redirect("Index.aspx");
                return;
            }
        }
    }
    protected void GetImagePath()
    {
        try
        {
            if (System.Configuration.ConfigurationManager.AppSettings["DelarLogo"].ToString() != "")
            {
                strDelarLogo = System.Configuration.ConfigurationManager.AppSettings["DelarLogo"].ToString();
                IMG2.Visible = true;
                IMG2.Src = strDelarLogo;
            }
            else
            {
                IMG2.Visible = false;
            }
        }
        catch (Exception ex)
        {
        }
    }
    protected void btnBack_Click(object sender, EventArgs e)
    {
        Response.Redirect("Index.aspx");
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            gstrServerName = Server.MachineName.ToString();
        }
        catch (Exception ex)
        {
            throw ex;
        }
        BuildDatabaseConnectionString();
        BuildDataProcessConnectionString();
        strDBExists = objCommon.CheckDatabaseExists(sbConnection.ToString());
        if (strDBExists == "0")
        {
            base.Message("Enter valid Database Connection information");
            return;
        }
        else if (strDBExists == "1")
        {
        }
        else
        {
            base.Message(strDBExists);
            return;
        }
        //Check the User is a valid Super Admin User Group User
        intSuperAdminUser = objCommon.CheckSuperAdminUser(sbConnection.ToString(), txtTCUserName.Text, txtTCPassword.Text);
        if (intSuperAdminUser == 0)
        {
            base.Message("Enter valid Timecheck Super Admin User Credentials");
            return;
        }
        //Get the Raw Data Service path with file name
        strRawDataFileName = GetRawDataServicePath();
        if (File.Exists(strRawDataFileName))
        {
            strRawDataFileType = Path.GetExtension(strRawDataFileName);
        }
        else
        {
            base.Message("Collect Raw Data File path not exists");
            return;
        }
        if (!strRawDataFileType.Equals(".config"))
        {
            base.Message("Not a valid Collect Raw Data Configuration file");
            return;
        }
        else
        {
            blnRawDataExists = CheckValidRawDataFile(strRawDataFileName);
        }
        if (blnRawDataExists == false)
        {
            base.Message("Not a valid Collect Raw Data Configuration file");
            return;
        }
        strDataProcessFileName = GetDataProcessServicePath();
        if (File.Exists(strDataProcessFileName))
        {
            strDataProcessFileType = Path.GetExtension(strDataProcessFileName);
        }
        else
        {
            base.Message("Data Process File path not exists");
            return;
        }
        if (!strDataProcessFileType.Equals(".config"))
        {
            base.Message("Not a valid Data Process Configuration file");
            return;
        }
        else
        {
            blnDataProcessExists = CheckValidDataProcessFile(strDataProcessFileName);
        }
        if (blnDataProcessExists == false)
        {
            base.Message("Not a valid Data Process Configuration file");
            return;
        }
        //Email Schedular File & Configuration File Path by Manjula.P on 18-Mar-2015
        strEmailSchedularFileName = GetEmailSchedularServicePath();
        if (File.Exists(strEmailSchedularFileName))
        {
            strEmailSchedularFileType = Path.GetExtension(strEmailSchedularFileName);
        }
        else
        {
            base.Message("Email Schedular File path not exists");
            return;
        }
        if (!strEmailSchedularFileType.Equals(".config"))
        {
            base.Message("Not a valid Email Schedular Configuration file");
            return;
        }
        else
        {
            blnEmailSchedularExists = CheckValidEmailShedularFile(strEmailSchedularFileName);
        }
        if (blnEmailSchedularExists == false)
        {
            base.Message("Not a valid Email Schedular Configuration file");
            return;
        }
        // end of Email Schedular File & Configuration File Path
        string strEncryptedConString = Cryptography.Encrypt(sbConnection.ToString(), gstrEncryptedKey);
        try
        {
            OverwriteApplicationConnectionString(strEncryptedConString);
            OverwriteRawDataConnectionString(strEncryptedConString);
            //For Email Schedular connection string override function call by Manjula.P on 18-Mar-2015
            OverwriteEmailSchedularConnectionString(strEncryptedConString);
            strEncryptedConString = Cryptography.Encrypt(sbDataProcessConnection.ToString(), gstrEncryptedKey);
            OverwriteDataProcessConnectionString(strEncryptedConString);
        }
        catch (Exception ex)
        {
            throw ex;
        }
        //Windows Services Stop and Start
        try
        {
            OverWriteRawDataStatus();
            //For Email Schedular
            OverWriteEmailSchedularStatus();
            OverWriteDataProcessStatus();
        }
        catch (Exception ex)
        {
            throw ex;
        }
        //Response.Redirect("Index.aspx");
        //return;
        try
        {
            base.MessageWithRedirect("Configuration Saved Successfully", "Index.aspx");
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    private void BuildDatabaseConnectionString()
    {
        sbConnection.Append("Data Source=");
        sbConnection.Append(txtServerName.Text.Trim().Replace("'", "''"));
        sbConnection.Append(";Initial Catalog=");
        sbConnection.Append(txtDatabaseName.Text.Trim().Replace("'", "''"));
        sbConnection.Append(";User ID=");
        sbConnection.Append(txtDBUserName.Text.Trim().Replace("'", "''"));
        sbConnection.Append(";pwd=");
        sbConnection.Append(txtDBPassword.Text.Trim().Replace("'", "''"));
        sbConnection.Append(";");
    }
    private void BuildDataProcessConnectionString()
    {
        sbDataProcessConnection.Append("Provider=SQLOLEDB.1;");
        sbDataProcessConnection.Append("Data Source=");
        sbDataProcessConnection.Append(txtServerName.Text.Trim().Replace("'", "''"));
        sbDataProcessConnection.Append(";Initial Catalog=");
        sbDataProcessConnection.Append(txtDatabaseName.Text.Trim().Replace("'", "''"));
        sbDataProcessConnection.Append(";User ID=");
        sbDataProcessConnection.Append(txtDBUserName.Text.Trim().Replace("'", "''"));
        sbDataProcessConnection.Append(";pwd=");
        sbDataProcessConnection.Append(txtDBPassword.Text.Trim().Replace("'", "''"));
        sbDataProcessConnection.Append(";");
    }

    //public void OverwriteApplicationConnectionString(string ConnStr)
    //{
    //    XmlDocument doc = new XmlDocument();
    //    string WebConfigFilename = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath).FilePath;
    //    doc.Load(WebConfigFilename);
    //    XmlNodeList oList = doc.SelectNodes("configuration/connectionStrings/add");
    //    for (int i = 0; i < oList.Count; i++)
    //    {
    //        XmlAttribute oKey = oList[i].Attributes["name"];
    //        XmlAttribute oValue = oList[i].Attributes["connectionString"];
    //        if (oKey.Value == "DBConnection")
    //        {
    //            oValue.Value = ConnStr;
    //        }
    //    }

    //    //Un comment the following while creating setup

    //    doc.Save(WebConfigFilename);
    //}

    public void OverwriteApplicationConnectionString(string ConnStr)
    {
        XmlDocument doc = new XmlDocument();
        string WebConfigFilename = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath).FilePath;
        doc.Load(WebConfigFilename);
        XmlNodeList oList = doc.SelectNodes("configuration/connectionStrings/add");
        for (int i = 0; i < oList.Count; i++)
        {
            XmlAttribute oKey = oList[i].Attributes["name"];
            XmlAttribute oValue = oList[i].Attributes["connectionString"];
            if (oKey.Value == "DBConnection")
            {
                oValue.Value = ConnStr;
            }
        }

        //Un comment the following while creating setup

        doc.Save(WebConfigFilename);
    }
    public void OverwriteRawDataConnectionString(string ConnStr)
    {
        XmlDocument doc = new XmlDocument();
        string WebConfigFilename = strRawDataFileName;
        doc.Load(WebConfigFilename);
        XmlNodeList oList = doc.SelectNodes("configuration/appSettings/add");
        for (int i = 0; i < oList.Count; i++)
        {
            XmlAttribute oKey = oList[i].Attributes["key"];
            XmlAttribute oValue = oList[i].Attributes["value"];
            if (oKey.Value == "ConnectionString")
            {
                oValue.Value = ConnStr;
            }
        }
        //Un comment the following while creating setup
        doc.Save(WebConfigFilename);
    }
    public void OverwriteDataProcessConnectionString(string ConnStr)
    {
        XmlDocument doc = new XmlDocument();
        string WebConfigFilename = strDataProcessFileName;
        doc.Load(WebConfigFilename);
        XmlNodeList oList = doc.SelectNodes("configuration/appSettings/add");
        for (int i = 0; i < oList.Count; i++)
        {
            XmlAttribute oKey = oList[i].Attributes["key"];
            XmlAttribute oValue = oList[i].Attributes["value"];
            if (oKey.Value == "ConnectionString")
            {
                oValue.Value = ConnStr;
            }
        }
        //Un comment the following while creating setup
        doc.Save(WebConfigFilename);
    }
    //Override Email Schedular service file path by Manjula.P on 18-Mar-2015
    public void OverwriteEmailSchedularConnectionString(string ConnStr)
    {
        XmlDocument doc = new XmlDocument();
        string WebConfigFilename = strEmailSchedularFileName;
        doc.Load(WebConfigFilename);
        XmlNodeList oList = doc.SelectNodes("configuration/appSettings/add");
        for (int i = 0; i < oList.Count; i++)
        {
            XmlAttribute oKey = oList[i].Attributes["key"];
            XmlAttribute oValue = oList[i].Attributes["value"];
            if (oKey.Value == "ConnectionString")
            {
                oValue.Value = ConnStr;
            }
        }
        //Un comment the following while creating setup
        doc.Save(WebConfigFilename);
    }
    //End Of Override Email Schedular service file path by Manjula.P on 18-Mar-2015
    public bool CheckValidRawDataFile(string strRawDataFileName)
    {
        blnRawDataExists = false;
        XmlDocument doc = new XmlDocument();
        doc.Load(strRawDataFileName);
        XmlNodeList oList = doc.SelectNodes("configuration/appSettings/add");
        if (oList.Count > 0)
        {
            for (int i = 0; i < oList.Count; i++)
            {
                XmlAttribute oKey = oList[i].Attributes["key"];
                XmlAttribute oValue = oList[i].Attributes["value"];
                if (oKey != null && oValue != null)
                {
                    if (oKey.Value == "ServiceName" && oValue.Value == "CollectRawDataService")
                    {
                        blnRawDataExists = true;
                    }
                }
            }
        }
        return blnRawDataExists;
    }
    //For email schedular file path validation
    public bool CheckValidEmailShedularFile(string strEmailSchedularFileName)
    {
        blnEmailSchedularExists = false;
        XmlDocument doc = new XmlDocument();
        doc.Load(strEmailSchedularFileName);
        XmlNodeList oList = doc.SelectNodes("configuration/appSettings/add");
        if (oList.Count > 0)
        {
            for (int i = 0; i < oList.Count; i++)
            {
                XmlAttribute oKey = oList[i].Attributes["key"];
                XmlAttribute oValue = oList[i].Attributes["value"];
                if (oKey != null && oValue != null)
                {
                    if (oKey.Value == "ServiceName" && oValue.Value == "ReportSchedular")
                    {
                        blnEmailSchedularExists = true;
                    }
                }
            }
        }
        return blnEmailSchedularExists;
    }
    //End of For email schedular file path validation
    public string GetRawDataServicePath()
    {
        string RawDataFileInfo = string.Empty;
        string[] fileArr = Directory.GetFiles(Server.MapPath("TimecheckCollectRawDataSetup"), "*.txt");
        int arrCount = fileArr.Length;
        if (arrCount > 0)
        {
            string RawDataFileName = fileArr[arrCount - 1].ToString();
            FileStream RawDataFileStream = new FileStream(RawDataFileName, FileMode.Open);
            StreamReader RawDataFileStreamReader = new StreamReader(RawDataFileStream);
            RawDataFileInfo = RawDataFileStreamReader.ReadToEnd();
            RawDataFileStreamReader.Close();
            RawDataFileStream.Close();
        }
        strRawDataFileName = RawDataFileInfo.ToString().Trim();
        return strRawDataFileName;
    }
    public string GetDataProcessServicePath()
    {
        string DataProcessFileInfo = string.Empty;
        string[] fileArr = Directory.GetFiles(Server.MapPath("TimecheckDataProcessSetup"), "*.txt");
        int arrCount = fileArr.Length;
        if (arrCount > 0)
        {
            string DataProcessFileName = fileArr[arrCount - 1].ToString();
            FileStream DataProcessFileStream = new FileStream(DataProcessFileName, FileMode.Open);
            StreamReader DataProcessFileStreamReader = new StreamReader(DataProcessFileStream);
            DataProcessFileInfo = DataProcessFileStreamReader.ReadToEnd();
            DataProcessFileStreamReader.Close();
            DataProcessFileStream.Close();
        }
        strDataProcessFileName = DataProcessFileInfo.ToString().Trim();
        return strDataProcessFileName;
    }
    //Getting Email Schedular Service File Path Function
    public string GetEmailSchedularServicePath()
    {
        string EmailSchedularFileInfo = string.Empty;
        string[] fileArr = Directory.GetFiles(Server.MapPath("TimecheckEmailSchedulerSetup"), "*.txt");
        int arrCount = fileArr.Length;
        if (arrCount > 0)
        {
            string EmailSchedularFileName = fileArr[arrCount - 1].ToString();
            FileStream EmailSchedularFileStream = new FileStream(EmailSchedularFileName, FileMode.Open);
            StreamReader EmailSchedularFileStreamReader = new StreamReader(EmailSchedularFileStream);
            EmailSchedularFileInfo = EmailSchedularFileStreamReader.ReadToEnd();
            EmailSchedularFileStreamReader.Close();
            EmailSchedularFileStream.Close();
        }
        strEmailSchedularFileName = EmailSchedularFileInfo.ToString().Trim();
        return strEmailSchedularFileName;
    }
    //End Of Getting Email Schedular Service File Path Function
    public bool CheckValidDataProcessFile(string strDataProcessFileName)
    {
        blnDataProcessExists = false;
        XmlDocument doc = new XmlDocument();
        doc.Load(strDataProcessFileName);
        XmlNodeList oList = doc.SelectNodes("configuration/appSettings/add");
        if (oList.Count > 0)
        {
            for (int i = 0; i < oList.Count; i++)
            {
                XmlAttribute oKey = oList[i].Attributes["key"];
                XmlAttribute oValue = oList[i].Attributes["value"];
                if (oKey != null && oValue != null)
                {
                    if (oKey.Value == "ServiceName" && oValue.Value == "DataProcessService")
                    {
                        blnDataProcessExists = true;
                    }
                }
            }
        }
        return blnDataProcessExists;
    }
    public void OverWriteRawDataStatus()
    {
        int intIndex = strRawDataFileName.LastIndexOf(@"\");
        string RawDataFile = strRawDataFileName.Substring(0, intIndex) + "\\RawData.txt";
        StreamWriter sw = File.CreateText(RawDataFile);
        sw.Write("Changed");
        sw.Flush();
        sw.Close();
    }
    public void OverWriteDataProcessStatus()
    {
        int intIndex = strDataProcessFileName.LastIndexOf(@"\");
        string DataProcessFile = strDataProcessFileName.Substring(0, intIndex) + "\\DataProcess.txt";
        StreamWriter sw = File.CreateText(DataProcessFile);
        sw.Write("Changed");
        sw.Flush();
        sw.Close();
    }
    //For Email Schedular change status
    public void OverWriteEmailSchedularStatus()
    {
        int intIndex = strEmailSchedularFileName.LastIndexOf(@"\");
        string EmailSchedularFile = strEmailSchedularFileName.Substring(0, intIndex) + "\\ReportFilePath.txt";
        StreamWriter sw = File.CreateText(EmailSchedularFile);
        sw.Write("Changed");
        sw.Flush();
        sw.Close();
    }
    //End Of For Email Schedular change status
    //Starting Windows services
    public void StartService(string strServiceDisplayName)
    {
        //string PcName = "Angler122";
        string PcName = gstrServerName;
        WindowsImpersonationContext wic = null;
        try
        {
            IPrincipal p = this.User;
            WindowsIdentity id = WindowsIdentity.GetCurrent();
            wic = id.Impersonate();
            ServiceController[] services = ServiceController.GetServices();
            for (int i = 0; i < services.Length; i++)
            {
                if (services[i].DisplayName == strServiceDisplayName)
                {
                    ServiceController sc = new ServiceController(services[i].DisplayName, PcName);
                    if (sc.Status == ServiceControllerStatus.Stopped)
                    {
                        sc.Start();
                    }
                }
            }
        }
        catch (Exception err)
        {
            Response.Write(err.Message);
        }
        finally
        {
            wic.Undo();
        }
    }
    //Starting Windows services
    public void StopService(string strServiceDisplayName)
    {
        string PcName = gstrServerName;
        WindowsImpersonationContext wic = null;
        try
        {
            WindowsIdentity id = WindowsIdentity.GetCurrent();
            wic = id.Impersonate();
            ServiceController[] services = ServiceController.GetServices();
            for (int i = 0; i < services.Length; i++)
            {
                if (services[i].DisplayName == strServiceDisplayName)
                {
                    ServiceController sc = new ServiceController(services[i].DisplayName, PcName);
                    if (sc.Status == ServiceControllerStatus.Running)
                    {
                        sc.Stop();
                    }
                }
            }
        }
        catch (Exception err)
        {
            Response.Write(err.Message);
        }
        finally
        {
            wic.Undo();
        }
    }
}
