using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OracleClient;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Configuration;
using System.Threading;
using System.Security.Cryptography;
using System.Text;
using Renci.SshNet;
using Renci.SshNet.Sftp;

public partial class SamaClaims : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            loadFiles();
            loadGCCFiles();
            loadFilesMD5();
            loadFilesProcessed();
            pnlGCC.Visible = false;
            ExceptionUtility.LogException(0, "", "33", "Page_Load", "");
        }
    }

    protected void rdMADAClaims_CheckedChanged(object sender, EventArgs e)
    {
        pnlGCC.Visible = false;
        pnlBR.Visible = true;
        lblError.Text = "";
        ExceptionUtility.LogException(0, "", "", "rdMADAClaims_CheckedChanged", "");
    }

    protected void rdGCCClaims_CheckedChanged(object sender, EventArgs e)
    {
        pnlGCC.Visible = true;
        pnlBR.Visible = false;
        lblError.Text = "";
        ExceptionUtility.LogException(0, "", "", "rdGCCClaims_CheckedChanged", "");
    }

    private void loadFiles()
    {
        try
        {
            string DBConnection = Helper.dbConnection();

            OracleConnection oracon = new OracleConnection(DBConnection);
            oracon.Open();

            OracleCommand oracom = new OracleCommand();
            oracom.Connection = oracon;

            oracom.CommandType = CommandType.StoredProcedure;
            oracom.CommandText = "poslookup_getter.get_dir_files";

            oracom.Parameters.Add("p_dir_list", OracleType.Cursor).Direction = ParameterDirection.Output;

            OracleDataAdapter da = new OracleDataAdapter(oracom);
            DataSet ds = new DataSet();
            da.Fill(ds);

            ddlFiles.DataSource = ds;
            ddlFiles.DataBind();

            oracon.Close();
            //ExceptionUtility.LogException("Success", "poslookup_getter.get_dir_files", "loadFiles", "");
        }
        catch (Exception ex)
        {
            ExceptionUtility.LogException(ex, "poslookup_getter.get_dir_files", "", "loadFiles", "");

        }
    }

    private void loadFiles1()
    {

        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        DataSet ds = new DataSet();

        try
        {

            oracom.CommandType = CommandType.StoredProcedure;
            oracom.CommandText = "poslookup_getter.get_dir_files";

            oracom.Parameters.Add("p_dir_list", OracleType.Cursor).Direction = ParameterDirection.Output;

            OracleDataAdapter da = new OracleDataAdapter(oracom);

            da.Fill(ds);
            ExceptionUtility.LogException(0, "poslookup_getter.get_dir_files", "", "loadFiles1", "");

        }
        catch (Exception ex)
        {
            if (ex.Message.Contains("ORA-24338: statement handle not executed"))
            {

            }
            else
            {
                ExceptionUtility.LogException(ex, "poslookup_getter.get_dir_files", "", "loadFiles1", "");

            }
        }

        oracon.Close();
        //ddlFiles.DataSource = ds;
        //ddlFiles.DataBind();     
    }

    private string getDir()
    {
        try
        {
            string DBConnection = Helper.dbConnection();

            OracleConnection oracon = new OracleConnection(DBConnection);
            oracon.Open();

            OracleCommand oracom = new OracleCommand();
            oracom.Connection = oracon;

            oracom.CommandType = CommandType.StoredProcedure;
            oracom.CommandText = "poslookup_getter.get_claim_dir";

            oracom.Parameters.Add("p_dir", OracleType.VarChar, 250).Direction = ParameterDirection.Output;

            oracom.ExecuteNonQuery();
            oracon.Close();

            string a = oracom.Parameters["p_dir"].Value.ToString();
            return a;
        }
        catch (Exception ex)
        {
            ExceptionUtility.LogException(ex, "poslookup_getter.get_claim_dir", "", "getDir", "");
            return null;
        }
    }

    private string getDBPath()
    {
        try
        {
            string DBConnection = Helper.dbConnection();

            OracleConnection oracon = new OracleConnection(DBConnection);
            oracon.Open();

            OracleCommand oracom = new OracleCommand();
            oracom.Connection = oracon;

            oracom.CommandType = CommandType.StoredProcedure;
            oracom.CommandText = "poslookup_getter.get_claim_path";

            oracom.Parameters.Add("p_path", OracleType.VarChar, 250).Direction = ParameterDirection.Output;

            oracom.ExecuteNonQuery();
            oracon.Close();

            string a = oracom.Parameters["p_path"].Value.ToString();
            return a;
        }
        catch (Exception ex)
        {
            ExceptionUtility.LogException(ex, "poslookup_getter.get_claim_dir", "", "getDir", "");
            return null;
        }
    }


    private void generateGCC()
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "samaclaims.Generate_GCCNETClm_OutFile";

        oracom.Parameters.Add("p_Filepath", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_file_name", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_ResMsg", OracleType.VarChar, 500).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;

        oracom.Parameters["p_Filepath"].Value = getDir();

        oracom.ExecuteNonQuery();
        oracon.Close();
        string respcode = oracom.Parameters["p_res_code"].Value.ToString();
        string resMsg = oracom.Parameters["p_ResMsg"].Value.ToString();

        if (respcode == "0")
        {
            lblError.Text = resMsg; // "generating Completed";
        }
        else
            lblError.Text = resMsg; // "no claims are generated";
    }

    protected void btnGenerateGCC_Click(object sender, EventArgs e)
    {
        generateGCC();
    }
    private void loadGCCFiles()
    {
        ddlGCCFiles.Items.Clear();
        DirectoryInfo di = new DirectoryInfo(ConfigurationSettings.AppSettings["CPS_P"]);
        FileInfo[] rgFiles = di.GetFiles("GCC*.csv");
        foreach (FileInfo fi in rgFiles)
        {
            ddlGCCFiles.Items.Add(fi.Name);
        }
    }

    protected void btnGCCDownload_Click(object sender, EventArgs e)
    {
        ExceptionUtility.LogException(0, "", "", "btnGCCDownload_Click", "Call:Start");

        if (ddlGCCFiles.Items.Count >= 1)
        {
            string aFile = ddlGCCFiles.SelectedValue;
            ExceptionUtility.LogException(0, "", "", "btnGCCDownload_Click", "Downloaded GCC File Name: " + aFile);

            string FilePath = ConfigurationSettings.AppSettings["CPS_P"];

            ExceptionUtility.LogException(0, "", "", "btnGCCDownload_Click", "The Selected File path name is  " + FilePath + aFile);

            if (File.Exists(FilePath + aFile))
            {
                lblError.Text = "GCC Claim File is transmitted...";
                Response.AppendHeader("Content-Disposition", "attachment; filename=" + aFile);
                Response.TransmitFile(FilePath + aFile);

                ExceptionUtility.LogException(0, "", "", "btnGCCDownload_Click", "The Selected File is tranmistted! ");
                ExceptionUtility.LogException(0, "", "", "btnGCCDownload_Click", "Call:End");
                Response.End();

            }
            else
            {
                lblError.Text = "The Selected File is not present in the Configured Download Path, Refer Configuration";
                ExceptionUtility.LogException(0, "", "", "btnGCCDownload_Click", "The Selected File is not present in the COnfigured Download Path, Refer Configuration! ");
            }
        }
        else
            ExceptionUtility.LogException(0, "", "", "btnGCCDownload_Click", "No File is selected to Download ");
        ExceptionUtility.LogException(0, "", "", "btnGCCDownload_Click", "Call:End");
        lblError.Text = "No File is available to Download";
    }
    protected void btnLoad_Click(object sender, EventArgs e)
    {
        if (ddlFiles.Items.Count > 0)
            load();
        else
            lblError.Text = "There are no files";
    }

    private void load()
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "samaclaims.loadsamaclaims";

        oracom.Parameters.Add("filepath", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("filename", OracleType.VarChar).Direction = ParameterDirection.Input;

        oracom.Parameters["filepath"].Value = getDir();
        oracom.Parameters["filename"].Value = ddlFiles.SelectedValue;

        oracom.ExecuteNonQuery();
        oracon.Close();
        lblError.Text = "loading Completed";
    }

    private void generate()
    {
        string DBConnection = Helper.dbConnection();

        OracleConnection oracon = new OracleConnection(DBConnection);
        oracon.Open();

        OracleCommand oracom = new OracleCommand();
        oracom.Connection = oracon;

        oracom.CommandType = CommandType.StoredProcedure;
        oracom.CommandText = "samaclaims.gensamaclaims";

        oracom.Parameters.Add("filepath", OracleType.VarChar).Direction = ParameterDirection.Input;
        oracom.Parameters.Add("p_ONfile_name", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_OFFfile_name", OracleType.VarChar, 250).Direction = ParameterDirection.Output;
        oracom.Parameters.Add("p_res_code", OracleType.Number).Direction = ParameterDirection.Output;

        oracom.Parameters["filepath"].Value = getDir();

        oracom.ExecuteNonQuery();
        oracon.Close();
        string a = oracom.Parameters["p_res_code"].Value.ToString();
        string onfileName = oracom.Parameters["p_ONfile_name"].Value.ToString();
        string offfileName = oracom.Parameters["p_OFFfile_name"].Value.ToString();
        //onfileName = "DONC20190502962578.CPS";
        if (a == "0")
        {
            string error = "";
            if (onfileName.Trim().Length != 0 || offfileName.Trim().Length != 0)
            {
                lblError.Text = "Generating Completed";

                string md5FilePath = ConfigurationManager.AppSettings["MD5EXEPATH"];


                if (downLoadFileFromSFTP(onfileName, offfileName, ref error))
                {
                    foreach (FileInfo f in new DirectoryInfo(ConfigurationManager.AppSettings["MD5EXEPATH"]).GetFiles("*.cps"))
                    {
                        if (!f.Name.Equals(onfileName) && !f.Name.Equals(offfileName))
                        {
                            try
                            {
                                f.Delete();
                            }
                            catch (Exception ex)
                            {
                            }
                        }
                        //if (!f.Name.Equals(fileName.Replace("ON", "OFF").Insert(fileName.Length - 3, "_edited")))
                        //f.Delete();

                    }
                    /*sat*/
                    // File.Move(filePath + FileName, md5FilePath + FileName);

                    if (onfileName.Trim().Length != 0)
                    {
                        byte[] array = File.ReadAllBytes(md5FilePath + onfileName);
                        if (array.Length > 1)
                        {
                            byte[] newArray = new byte[array.Length - 1];
                            Array.Copy(array, newArray, array.Length - 1);
                            File.WriteAllBytes(md5FilePath + onfileName, newArray);
                        }
                    }
                    //File.Move(filePath + offFileName, md5FilePath + offFileName);
                    if (offfileName.Trim().Length != 0)
                    {

                        byte[] array_off = File.ReadAllBytes(md5FilePath + offfileName);
                        if (array_off.Length > 1)
                        {
                            byte[] newArray_off = new byte[array_off.Length - 1];
                            Array.Copy(array_off, newArray_off, array_off.Length - 1);
                            File.WriteAllBytes(md5FilePath + offfileName, newArray_off);
                        }

                    }
                    /*end */
                    //RunMD5(FileName);
                    //FileUtilityDLL.CPSFileReceiver cfr =
                    //    new FileUtilityDLL.CPSFileReceiver(downloadPath, fileName);claim_process.pks

                    //lnkFile.NavigateUrl = downloadVirtualPath + fileName;    
                    ////lnkFile.NavigateUrl = downloadVirtualPath + "PONC20140608170343.cps"; 
                    //lnkFile.Text = "Download Generated File : " + fileName;
                    //lnkFile.Visible = true;
                    lblError.Text = "Generated";
                }
                else
                    lblError.Text = error;
            }
            else
                lblError.Text = "no claims are generated";

        }
        else
        {
            lblError.Text = "no claims are generated";

        }
    }

    private bool downLoadFileFromSFTP(string onfile, string offfile, ref string error)
    {
        ExceptionUtility.LogEvent_Errors(0, "", "downLoadFileFromSFTP", "Start");

        string ftpServer = ConfigurationManager.AppSettings["SFTPServer"];


        //   string UserName = DecryptLibrary.DecryptLibrary.DecryptData(ConfigurationSettings.AppSettings["SFTPUserName"]);
        // string Pwd = DecryptLibrary.DecryptLibrary.DecryptData(ConfigurationSettings.AppSettings["SFTPPwd"]);
        string UserName, Pwd;
        if (ConfigurationSettings.AppSettings["SFTP_Encrypt"] as string == "NO")
        {
            UserName = ConfigurationSettings.AppSettings["SFTPUserName"] as string;
            Pwd = ConfigurationSettings.AppSettings["SFTPPwd"] as string;
        }
        else
        {
            UserName = DecryptLibrary.DecryptLibrary.DecryptData(ConfigurationSettings.AppSettings["SFTPUserName"]);
            Pwd = DecryptLibrary.DecryptLibrary.DecryptData(ConfigurationSettings.AppSettings["SFTPPwd"]);
        }

        string ftpDirectory = getDBPath(); //The directory in SFTP server where the files are present
        string LocalDirectory = ConfigurationManager.AppSettings["MD5EXEPATH"];

        try
        {
            var methods = new List<AuthenticationMethod>();
            methods.Add(new PasswordAuthenticationMethod(UserName, Pwd));

            var con = new ConnectionInfo(ftpServer, 22, UserName, methods.ToArray());


            using (var client = new SftpClient(con))
            {
                client.Connect();
                ExceptionUtility.LogEvent_Errors(0, "", "downLoadFileFromSFTP", "Connected");

                var FileList = client.ListDirectory(ftpDirectory);



                foreach (var file in FileList)
                {
                    //if (file.Name != "." && file.Name != ".." && file.Name != "Processed")
                    if (file.Name == onfile || file.Name == offfile)
                    {
                        if (!File.Exists(LocalDirectory + "/" + file.Name))
                        {
                            using (var fs = new FileStream(LocalDirectory + file.Name, FileMode.Create))
                            {
                                client.DownloadFile(file.FullName, fs);
                                ExceptionUtility.LogEvent_Errors(0, "", "downLoadFileFromSFTP", "Downloaded: " + file.FullName);
                                Thread.Sleep(100);
                            }
                        }
                        else
                            ExceptionUtility.LogEvent_Errors(0, "", "downLoadFileFromSFTP", "File Already Exist: " + file.FullName);
                    }
                }

                client.Disconnect();
            }
            ExceptionUtility.LogEvent_Errors(0, "", "downLoadFileFromSFTP", "End");

            return true;
        }
        catch (Exception ex)
        {
            error = ex.Message + ex.InnerException;
            ExceptionUtility.LogException(ex);
            return false;
        }
    }

    protected void btnGenerate_Click(object sender, EventArgs e)
    {
        generate();
        loadFilesMD5();
    }

    private bool uploadFileToSFTP(ref string error)
    {
        ExceptionUtility.LogEvent_Errors(0, "", "uploadFileToSFTP", "Start");

        string ftpServer = ConfigurationManager.AppSettings["SFTPServer"];

        string UserName, Pwd;
        if (ConfigurationSettings.AppSettings["SFTP_Encrypt"] as string == "NO")
        {
            UserName = ConfigurationSettings.AppSettings["SFTPUserName"] as string;
            Pwd = ConfigurationSettings.AppSettings["SFTPPwd"] as string;
        }
        else
        {
            UserName = DecryptLibrary.DecryptLibrary.DecryptData(ConfigurationSettings.AppSettings["SFTPUserName"]);
            Pwd = DecryptLibrary.DecryptLibrary.DecryptData(ConfigurationSettings.AppSettings["SFTPPwd"]);

            ExceptionUtility.LogEvent_Errors(0, "", "uploadFileToSFTP", "sftp:" + UserName.Substring(0, 3) + ":" + Pwd.Substring(0, 3));

        }

        try
        {
            string onlyfileName = FileUpload1.FileName.Replace(" ", "");
            string uploadPath = ConfigurationSettings.AppSettings["CPS_D"];
            string fileName = uploadPath + onlyfileName;
            if (!File.Exists(fileName))
            {
                FileUpload1.SaveAs(fileName);
                ExceptionUtility.LogEvent_Errors(0, "", "uploadFileToSFTP", "File Save as " + fileName);

                string uploadPathVirtual = getDBPath();

                var methods = new List<AuthenticationMethod>();
                methods.Add(new PasswordAuthenticationMethod(UserName, Pwd));

                var con = new ConnectionInfo(ftpServer, 22, UserName, methods.ToArray());

                using (var client = new SftpClient(con))
                {
                    client.Connect();
                    Console.WriteLine("");
                    ExceptionUtility.LogEvent_Errors(0, "", "uploadFileToSFTP", "SftpClient Successfully Connected");

                    //string uploadfn = "Upload.txt";
                    client.ChangeDirectory(uploadPathVirtual);//change if required
                    using (var uplfileStream = System.IO.File.OpenRead(fileName))
                    {

                        client.UploadFile(uplfileStream, onlyfileName, true);
                        ExceptionUtility.LogEvent_Errors(0, "", "uploadFileToSFTP", onlyfileName + " Uploaded");


                    }
                    client.Disconnect();
                }

                using (var sshClient = new SshClient(con))
                {
                    sshClient.Connect();
                    var cmd = sshClient.RunCommand("chmod 777 " + uploadPathVirtual + onlyfileName);
                    ExceptionUtility.LogEvent_Errors(0, "", "uploadFileToSFTP", onlyfileName + " Permission granted");

                    var output = cmd.Result;

                    sshClient.Disconnect();
                }

                File.Delete(fileName);

                ExceptionUtility.LogEvent_Errors(0, "", "uploadFileToSFTP", "End");

                return true;
            }
            else
                return false;

        }
        catch (Exception ex)
        {
            error = ex.Message;
            ExceptionUtility.LogException(ex);
            return false;
        }

    }

    protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            string error = "";
            string[] validFileTypes = { "cps" };//, "gif", "png", "jpg", "jpeg", "doc", "xls" };
            string ext = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName);
            bool isValidFile = false;
            int count = FileUpload1.FileName.Split('.').Length;
            if (count > 2)
            {
                lblError.Text = "Uploaded file has more than one extension. Please check the file and upload again";
                return;
            }
            for (int i = 0; i < validFileTypes.Length; i++)
            {
                if (ext == "." + validFileTypes[i])
                {
                    isValidFile = true;
                    break;
                }
            }
            if (!isValidFile)
            {
                lblError.ForeColor = System.Drawing.Color.Red;
                lblError.Text = "Invalid File. Please upload a File with extension " +
                               string.Join(",", validFileTypes);

            }
            else
            {
                //uploadFile();
                if (uploadFileToSFTP(ref  error))
                {
                    loadFiles();
                    lblError.Text = "Successfully Uploaded";
                }
                else
                    lblError.Text = error;
            }

        }
        else
            lblError.Text = "Please choose a file";
    }

    private void uploadFile()
    {
        string uploadPath = ConfigurationSettings.AppSettings["CPS_D"];
        if (File.Exists(uploadPath + FileUpload1.FileName.Replace(" ", "")))
            lblError.Text = "file already exists";
        else
        {
            FileUpload1.SaveAs(uploadPath + FileUpload1.FileName.Replace(" ", ""));
            //FileUtilityDLL.CPSFileSender cfs =
            //    new FileUtilityDLL.CPSFileSender(uploadPath, FileUpload1.FileName.Replace(" ", ""));
            //loadFiles();
            lblError.Text = "CPS File Uploaded...";// and being transfered to the files list. Please wait for a few seconds and refresh the page";
        }
    }


    //////////// MD5

    private void loadFilesMD5()
    {
        ddlFilesMD5.Items.Clear();
        DirectoryInfo di = new DirectoryInfo(ConfigurationSettings.AppSettings["MD5EXEPATH"]);
        FileInfo[] rgFiles = di.GetFiles("*.CPS");
        foreach (FileInfo fi in rgFiles)
        {
            if (!fi.Name.Substring(fi.Name.Length - 8).Contains("-MD5.cps"))
                ddlFilesMD5.Items.Add(fi.Name);
        }
    }

    private void loadFilesProcessed()
    {
        ddlProcessedFiles.Items.Clear();
        DirectoryInfo di = new DirectoryInfo(ConfigurationSettings.AppSettings["CPS_DONE"]);
        FileInfo[] rgFiles = di.GetFiles("*.CPS");
        foreach (FileInfo fi in rgFiles)
        {
            if (!fi.Name.Substring(fi.Name.Length - 8).Contains("-MD5.cps"))
                ddlProcessedFiles.Items.Add(fi.Name);
        }
    }

    protected void btnGenerateMD5_Click(object sender, EventArgs e)
    {

        generate_MDS1();
    }

    private void generate_MDS1()
    {
        string fileName;
        string md5FilePath = ConfigurationManager.AppSettings["MD5EXEPATH"];
        string processedPath = ConfigurationManager.AppSettings["CPS_DONE"];
        string md5exe = ConfigurationManager.AppSettings["MD5EXE"];

        string outfilename_MD5 = ddlFilesMD5.SelectedValue.Insert(ddlFilesMD5.SelectedValue.Length - 4, "-MD5");

        if (!GetMd5Hash(md5FilePath + ddlFilesMD5.SelectedValue, md5FilePath + outfilename_MD5, false))
        {
            lblError.Text = "Failed to Generate MD5";
            return;
        }

        lblError.Text = "MD5 file generated successfully";
        loadFilesMD5();
        loadFilesProcessed();
        //Process.Start(md5exe, ddlFilesMD5.SelectedValue);
        //Thread.Sleep(2000);
        if (File.Exists(md5FilePath + outfilename_MD5))
        {
            File.Move(md5FilePath + ddlFilesMD5.SelectedValue, processedPath + ddlFilesMD5.SelectedValue);
            fileName = ddlFilesMD5.SelectedValue.Insert(ddlFilesMD5.SelectedValue.Length - 4, "-MD5");
            Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName + "");
            Response.TransmitFile(md5FilePath + fileName);
            Response.End();
        }
        else
            lblError.Text = "MD5 File is not generated..";
        
    }

    public bool GetMd5Hash(string strInFileName, string stroutFileName, bool bIgnoreLastChar)
    {

        try
        {
            MD5 md5Hash = MD5.Create();


            string strInput = System.IO.File.ReadAllText(strInFileName);


            if (bIgnoreLastChar && strInput[strInput.Length - 1] == '\n')
            {
                strInput = strInput.Substring(0, strInput.Length - 1);

            }

            // Convert the input string to a byte array and compute the hash.
            byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(strInput));

            // Create a new Stringbuilder to collect the bytes
            // and create a string.
            StringBuilder sBuilder = new StringBuilder();

            // Loop through each byte of the hashed data 
            // and format each one as a hexadecimal string.
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }
            System.IO.File.WriteAllText(stroutFileName, sBuilder.ToString());
            // Return the hexadecimal string.
            return true;
        }
        catch (Exception ex)
        {
            ExceptionUtility.LogException(ex, "", "36", "GetMd5Hash", "");
            return false;
        }
    }

    protected void GenerateMD5(bool bIgnoreLastChar)
    {
        try
        {

            string cps_p_dir, cps_iis;
            cps_p_dir = ConfigurationSettings.AppSettings["CPS_P"];
            cps_iis = ConfigurationSettings.AppSettings["CPS_P_IIS"];


            string inFileName_CPS = ddlFiles.SelectedValue;
            string outfilename_MD5 = ddlFiles.SelectedValue.Insert(ddlFiles.SelectedValue.Length - 4, "-MD5");

            if (!GetMd5Hash(cps_p_dir + "\\" + inFileName_CPS, cps_p_dir + "\\" + outfilename_MD5, false))
            {
                lblError.Text = "Failed to Generate MD5";
                return;
            }

            lblError.Text = "MD5 file generated successfully";



            bool loop = true;

            for (int i = 0; i < 5 && loop; i++)
            {
                try
                {
                    Thread.Sleep(5000);

                    File.Move(ConfigurationSettings.AppSettings["CPS_P"] + "\\" + outfilename_MD5, ConfigurationSettings.AppSettings["CPS_P_IIS"] + "\\" + outfilename_MD5);
                    loop = false;
                }
                catch (Exception ex)
                {
                    ExceptionUtility.LogException(ex, "", "36", "btnSearch_Click - Delay", outfilename_MD5);
                }
            }
            loop = true;
            for (int i = 0; i < 5 && loop; i++)
            {
                try
                {
                    Thread.Sleep(5000);
                    File.Move(ConfigurationSettings.AppSettings["CPS_P"] + "\\" + inFileName_CPS,
                        ConfigurationSettings.AppSettings["CPS_P_IIS"] + "\\" + inFileName_CPS);
                    loop = false;
                }
                catch (Exception exx)
                {
                    ExceptionUtility.LogException(exx, "", "36", "btnSearch_Click - Delay", inFileName_CPS);
                }
            }

            //    lnkCPS.NavigateUrl = ConfigurationSettings.AppSettings["CPS_P_IIS_V"] + inFileName_CPS;
            //    lnkMD5.NavigateUrl = ConfigurationSettings.AppSettings["CPS_P_IIS_V"] + outfilename_MD5;
            Session["CPS_File"] = inFileName_CPS;
            Session["MD5_File"] = outfilename_MD5;

            //links.Visible = true;

            loadFiles();
            //loadFiles2();
            ExceptionUtility.LogException(0, "", "", "btnSearch_Click", "");
        }
        catch (Exception ex)
        {
            lblError.Text = "File Not Generated. Error happened during the execution of the MD5 exe";
            ExceptionUtility.LogException(ex, "", "", "btnSearch_Click", "");
        }

    }

    protected void btnDownloadMD5_Click(object sender, EventArgs e)
    {
        string md5FilePath = ConfigurationManager.AppSettings["MD5EXEPATH"];
        Response.AppendHeader("Content-Disposition", "attachment; filename=" + ddlFilesMD5.SelectedValue);
        Response.TransmitFile(md5FilePath + ddlFilesMD5.SelectedValue);
        Response.End();
    }

    protected void btnDownloadProcessed_Click(object sender, EventArgs e)
    {
        string md5FilePath = ConfigurationManager.AppSettings["CPS_DONE"];
        Response.AppendHeader("Content-Disposition", "attachment; filename=" + ddlProcessedFiles.SelectedValue);
        Response.TransmitFile(md5FilePath + ddlProcessedFiles.SelectedValue);
        Response.End();
    }

    protected void GenerateMD5_WithEXE()
    {
        try
        {
            string md5_dir = ConfigurationSettings.AppSettings["MD5EXE"];
            System.Diagnostics.Process.Start(ConfigurationSettings.AppSettings["MD5EXE"],
                ddlFiles.SelectedValue);
            lblError.Text = "MD5 file generated successfully";

            bool finish = true;

            string filename, cps_p_dir, cps_iis;

            while (finish)
            {
                try
                {
                    filename = ddlFiles.SelectedValue.Insert(ddlFiles.SelectedValue.Length - 4, "-MD5");
                    cps_p_dir = ConfigurationSettings.AppSettings["CPS_P"];
                    cps_iis = ConfigurationSettings.AppSettings["CPS_P_IIS"];
                    File.Move(ConfigurationSettings.AppSettings["CPS_P"] + "\\" + ddlFiles.SelectedValue.Insert(ddlFiles.SelectedValue.Length - 4, "-MD5"),
                        ConfigurationSettings.AppSettings["CPS_P_IIS"] + "\\" + ddlFiles.SelectedValue.Insert(ddlFiles.SelectedValue.Length - 4, "-MD5"));
                    finish = false;
                }
                catch (Exception exx)
                {

                }
            }

            finish = true;
            while (finish)
            {
                try
                {

                    File.Move(ConfigurationSettings.AppSettings["CPS_P"] + "\\" + ddlFiles.SelectedValue,
                        ConfigurationSettings.AppSettings["CPS_P_IIS"] + "\\" + ddlFiles.SelectedValue);
                    finish = false;
                }
                catch (Exception exx)
                {

                }
            }

            //     lnkCPS.NavigateUrl = ConfigurationSettings.AppSettings["CPS_P_IIS_V"] + ddlFiles.SelectedValue;
            //    lnkMD5.NavigateUrl = ConfigurationSettings.AppSettings["CPS_P_IIS_V"] + ddlFiles.SelectedValue.Insert(ddlFiles.SelectedValue.Length - 4, "-MD5");
            Session["CPS_File"] = ddlFiles.SelectedValue;
            Session["MD5_File"] = ddlFiles.SelectedValue.Insert(ddlFiles.SelectedValue.Length - 4, "-MD5");

            //links.Visible = true;

            loadFiles();
            //loadFiles2();
            ExceptionUtility.LogException(0, "", "", "btnSearch_Click", "");
        }
        catch (Exception ex)
        {
            lblError.Text = "File Not Generated. Error happened during the execution of the MD5 exe";
            ExceptionUtility.LogException(ex, "", "", "btnSearch_Click", "");
        }

    }

    

    private void generate_MDS()
    {
        string fileName;
        string md5FilePath = ConfigurationManager.AppSettings["MD5EXEPATH"];
        string md5exe = ConfigurationManager.AppSettings["MD5EXE"];
        //File.Move(filePath + ddlCPSPFiles .SelectedValue , md5FilePath + ddlCPSPFiles .SelectedValue );
        //File.Move(filePath + "PONC20140907144442.cps", md5FilePath + "PONC20140907144442.cps");
        //Process.Start(md5exe, FileName);  
        //Process.Start(md5exe, "PONC20140907144442.cps");
        //Response.AppendHeader("Content-Disposition", "attachment; filename=" + "PONC20140907144442-MD5.cps" + "");
        //Response.TransmitFile(md5FilePath + "PONC20140907144442-MD5.cps");

        Process.Start(md5exe, ddlFilesMD5.SelectedValue);
        Thread.Sleep(2000);
        if (File.Exists(md5FilePath + ddlFilesMD5.SelectedValue.Insert(ddlFilesMD5.SelectedValue.Length - 4, "-MD5")))
        {
            File.Delete(md5FilePath + ddlFilesMD5.SelectedValue);
            fileName = ddlFilesMD5.SelectedValue.Insert(ddlFilesMD5.SelectedValue.Length - 4, "-MD5");
            Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName + "");
            Response.TransmitFile(md5FilePath + fileName);
            Response.End();
        }
        else
            lblError.Text = "MD5 File is not generated..";
    }
}