Tuesday, December 4, 2018

CSV file replace with a datatble functionality


        private int CSVReplace(DataTable dtDictionary, string path, bool chkCase)
        {
            int totalcount = 0;
            try
            {
                string[] input = File.ReadAllLines(path);
                string inputLine = "";
                for (int i = 0; i < dtDictionary.Rows.Count; i++)
                {
                    if (dtDictionary.Rows[i].ItemArray[0].ToString().Trim() != "")
                    {
                        for (int k = 0; k < input.Count(); k++)
                        {
                            StringReader reader = new StringReader(input[k]);
                            List<List<string>> data = new List<List<string>>();
                            string[] inputArray = { };
                            while ((inputLine = reader.ReadLine()) != null)
                            {
                                if (inputLine.Trim().Length > 0)
                                {
                                    inputArray = inputLine.Split(new char[] { '|' });
                                    for (int j = 0; j < inputArray.Count(); j++)
                                    {
                                        int count = 0;
                                        if (chkCase)
                                        {
                                            if (inputArray[j] == dtDictionary.Rows[i].ItemArray[0].ToString().Trim())
                                            {
                                                count = count + 1;
                                                totalcount = totalcount + count;
                                                if (input[k].Contains(dtDictionary.Rows[i].ItemArray[0].ToString().Trim()))
                                                {
                                                    input[k] = input[k].Replace(dtDictionary.Rows[i].ItemArray[0].ToString().Trim(), dtDictionary.Rows[i].ItemArray[1].ToString().Trim() + ".");
                                                }
                                            }
                                        }
                                        else
                                        {
                                            if (inputArray[j].ToLower() == dtDictionary.Rows[i].ItemArray[0].ToString().Trim().ToLower())
                                            {
                                                count = count + 1;
                                                totalcount = totalcount + count;
                                                if (input[k].Contains(dtDictionary.Rows[i].ItemArray[0].ToString().Trim()))
                                                {
                                                    input[k] = Regex.Replace(input[k], dtDictionary.Rows[i].ItemArray[0].ToString().Trim(), dtDictionary.Rows[i].ItemArray[1].ToString().Trim() + ".", RegexOptions.IgnoreCase);
                                                }
                                            }
                                        }
                                        if (count > 0)
                                        {
                                            File.WriteAllLines(path, input);
                                            Log.WriteLog(Path.GetFileName(txtTarget.Text) + " target file replaced with " + Path.GetFileName(txtDictionary.Text) + " : Replaced " + count + " entries from " + dtDictionary.Rows[i].ItemArray[0].ToString() + " to " + dtDictionary.Rows[i].ItemArray[1].ToString());
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteLog("CSVReplace at Replace" + ex.Message);
            }
            return totalcount;
        }

Excel file replace with a datatable

 #region if target file is excel then the replace method
        /// <summary>
        /// ExcelReplace
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="boolCase"></param>
        /// <returns></returns>
        private double ExcelReplace(System.Data.DataTable dt, string path, bool boolCase)
        {
            double inttotalCount = 0;
            try
            {
                Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
                Workbook wb = excelApp.Workbooks.Open(path, Type.Missing, Type.Missing,
                                                       Type.Missing, Type.Missing,
                                                       Type.Missing, Type.Missing,
                                                       Type.Missing, Type.Missing,
                                                       Type.Missing, Type.Missing,
                                                       Type.Missing, Type.Missing,
                                                       Type.Missing, Type.Missing);
                excelApp.DisplayAlerts = false;

                Sheets ws = wb.Worksheets;
                Worksheet worksheet = (Worksheet)ws.get_Item(1);//1st sheet in workbook

                Range range = worksheet.UsedRange;//Used cells range

                int rows = range.Rows.Count;
                int cols = range.Columns.Count;

                Range startCell = worksheet.Cells[1, 1];
                Range endCell = worksheet.Cells[rows, cols];

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    double cnt = 0;
                    //matching words count based on case sensitive

                    if (dt.Rows[i].ItemArray[0].ToString().Trim() != "")
                    {

                        if (boolCase == true)
                        {

                            //excelApp.WorksheetFunction.SumProduct(range , pattern);
                            cnt = worksheet.Evaluate(excelApp.WorksheetFunction.CountIf(range, dt.Rows[i].ItemArray[0].ToString().Trim()));
                            // cnt = Regex.Matches(worksheet.Range[startCell, endCell].ToString(), dt.Rows[i].ItemArray[0].ToString().Trim()).Count;
                            //worksheet.Range[startCell, endCell].Replace(pattern, dt.Rows[i].ItemArray[1].ToString());

                            //cnt = excelApp.WorksheetFunction.SumIf(range, dt.Rows[i].ItemArray[0].ToString().Trim());//Case sensitive
                            //  cnt = Regex.Matches(File.ReadAllText(txtTarget.Text),pattern).Count;
                            //cnt = excelApp.WorksheetFunction.SumProduct("(--Exact("+range , dt.Rows[i].ItemArray[0].ToString().Trim()+"))"+);//Case sensitive

                            //cnt= worksheet.Evaluate("excelApp.WorksheetFunction.SumProduct(--Exact(range, dt.Rows[i].ItemArray[0].ToString().Trim()))");
                            //cnt = excelApp.WorksheetFunction.CountIfs(range, dt.Rows[i].ItemArray[0].ToString().Trim(), " --MatchCase: boolCase"); //"*"+dt.Rows[i].ItemArray[0].ToString()+"*"

                        }
                        else
                        {
                            cnt = excelApp.WorksheetFunction.CountIf(range, dt.Rows[i].ItemArray[0].ToString().Trim()); //"*"+dt.Rows[i].ItemArray[0].ToString()+"*"
                                                                                                                        //  cnt = Regex.Matches(File.ReadAllText(txtTarget.Text), Regex.Escape(dt.Rows[i].ItemArray[0].ToString().Trim()), RegexOptions.IgnoreCase).Count;
                        }

                    }
                    if (cnt != 0)
                    {
                        try
                        {
                            //replace the words based on case sensitive
                            worksheet.Range[startCell, endCell].Replace(dt.Rows[i].ItemArray[0].ToString(), dt.Rows[i].ItemArray[1].ToString(), MatchCase: boolCase);
                            // MessageBox.Show("Replaced " + cnt + " entries from " + dt.Rows[i].ItemArray[0].ToString() + " to " + dt.Rows[i].ItemArray[1].ToString());
                            Log.WriteLog(Path.GetFileName(path) + " target file replaced with " + Path.GetFileName(txtDictionary.Text) + " : Replaced " + cnt + " entries from " + dt.Rows[i].ItemArray[0].ToString() + " to " + dt.Rows[i].ItemArray[1].ToString());
                        }
                        catch (Exception ex)
                        {
                            cnt = 0;
                            Log.WriteLog("ExcelReplace at Replace" + ex.Message);
                            MessageBox.Show(ex.Message);
                        }
                    }
                    //for total matched words in the file
                    inttotalCount = inttotalCount + cnt;
                }
                wb.Close(true);
                excelApp.Quit();
            }
            catch (Exception ex)
            {
                Log.WriteLog("ExcelReplace" + ex.Message);
                MessageBox.Show(ex.Message);
            }
            if (inttotalCount == 0)
            {
                File.Delete(path);
            }

            return inttotalCount;
        }

        #endregion

Replace a file with a datatable

 private void BtnExecute_Click(object sender, EventArgs e)
        {
            if (txtDictionary.Text != "" && txtTarget.Text != "")
            {
                string newPath = Path.GetFullPath(Path.Combine(txtTarget.Text, @"..\"));//to go back from current directory
                string filename = Path.GetFileName(txtTarget.Text); //to get the filename
                try
                {
                    System.Data.DataTable dtDictionary = new System.Data.DataTable();
                    dtDictionary = ReadExcel(txtDictionary.Text);

                    if (dtDictionary.Columns.Count == 2)
                    {
                        System.IO.Directory.CreateDirectory(newPath + "ReplacedTarget"); // To create folder if it doesn't exists                     
                        string fileExt = Path.GetExtension(txtTarget.Text); //get the file extension 
                        double totalCount = 0;
                        File.Copy(txtTarget.Text, newPath + "\\ReplacedTarget\\" + filename); //copying target file

                     
                            for (int i = 0; i < dtDictionary.Rows.Count; i++)
                            {
                                if (dtDictionary.Rows[i].ItemArray[0].ToString().Trim() != "")
                                {
                                    int cnt = 0;
                                    try
                                    {
                                        string pattern = string.Format(@"\b{0}\b", dtDictionary.Rows[i].ItemArray[0].ToString().Trim());//to replace the whole word instead of part of a word

                                        if (chkCase.Checked == true)
                                        {
                                            //To get the matched words count in dictionary and target
                                            cnt = Regex.Matches(File.ReadAllText(txtTarget.Text), pattern).Count;
                                            if (cnt > 0)
                                            {
                                                //To replace matched words
                                                File.WriteAllText(newPath + "ReplacedTarget\\" + filename, File.ReadAllText(newPath + "ReplacedTarget\\" + filename).Replace(pattern, dtDictionary.Rows[i].ItemArray[1].ToString()));
                                            }
                                        }
                                        else
                                        {
                                            //To get the matched words count in dictionary and target irrespective of case
                                            cnt = Regex.Matches(File.ReadAllText(txtTarget.Text), pattern, RegexOptions.IgnoreCase).Count;

                                            if (cnt > 0)
                                            {
                                                //To replace matched words irrespective of case
                                                File.WriteAllText(newPath + "ReplacedTarget\\" + filename, Regex.Replace(File.ReadAllText(newPath + "ReplacedTarget\\" + filename), pattern, dtDictionary.Rows[i].ItemArray[1].ToString(), RegexOptions.IgnoreCase));
                                                Log.WriteLog(Path.GetFileName(txtTarget.Text) + " target file replaced with " + Path.GetFileName(txtDictionary.Text) + " : Replaced " + cnt + " entries from " + dtDictionary.Rows[i].ItemArray[0].ToString() + " to " + dtDictionary.Rows[i].ItemArray[1].ToString());
                                            }
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        cnt = 0;
                                        Log.WriteLog("BtnExecute_Click at WriteAllText" + ex.Message);
                                        MessageBox.Show(ex.Message);
                                    }
                                    //for total matched words in the file
                                    totalCount = totalCount + cnt;
                                }
                            }
                   
                        btnExecute.Enabled = false;
                        if (totalCount == 0)
                        {
                            File.Delete(newPath + "\\ReplacedTarget\\" + filename);
                        }

                        MessageBox.Show(totalCount + " total replacements completed");
                        Log.WriteLog(Path.GetFileName(txtTarget.Text) + " target file replaced with " + Path.GetFileName(txtDictionary.Text) + " : " + totalCount + " total replacements completed.\n");
                    }
                    else
                    {
                        MessageBox.Show("The excel sheet columns are not 2, Please select exact one.");
                        Log.WriteLog(Path.GetFileName(txtDictionary.Text) + " excel sheet columns are not 2, Please select exact one.");
                    }
                }
                catch (Exception ex)
                {
                    Log.WriteLog("BtnExecute_Click" + ex.Message);
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    foreach (Process process in Process.GetProcesses())
                    {
                        if (process.MainWindowTitle.Contains(txtDictionary.Text) || process.MainWindowTitle.Contains(txtTarget.Text))
                        {
                            process.Kill();
                            break;
                        }
                    }
                }
            }
            else
            {
                MessageBox.Show("please select Dictionary/Target files to proceed");
                Log.WriteLog("please select Dictionary/Target files to proceed");
            }
        }

Dialogbox

 private string GetFilePath()
        {
            string filePath = string.Empty;
            string fileExt = string.Empty;
            OpenFileDialog file = new OpenFileDialog(); //open dialog to choose file 
            try
            {
                if (file.ShowDialog() == System.Windows.Forms.DialogResult.OK) //if there is a file choosen by the user 
                {
                    filePath = file.FileName; //get the path of the file 
                    btnExecute.Enabled = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
                file.Dispose();
            }
            return filePath;
        }

Read the Excel file into datatable conversion

 public System.Data.DataTable ReadExcel(string filePath)
        {
            System.Data.DataTable dtexcel = new System.Data.DataTable();
            try
            {
                bool hasHeaders = false;
                string HDR = hasHeaders ? "Yes" : "No";
                string strConn;
                if (filePath.Substring(filePath.LastIndexOf('.')).ToLower() == ".xlsx")
                {
                    strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0;HDR=" + HDR + ";IMEX=0\"";
                }
                else
                {
                    strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=\"Excel 8.0;HDR=" + HDR + ";IMEX=0\"";
                }
                OleDbConnection conn = new OleDbConnection(strConn);
                conn.Open();
                System.Data.DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
                DataRow schemaRow = schemaTable.Rows[0];
                string sheet = schemaRow["TABLE_NAME"].ToString();
                if (!sheet.EndsWith("_"))
                {
                    string query = "SELECT  * FROM [" + sheet + "]";
                    OleDbDataAdapter daexcel = new OleDbDataAdapter(query, conn);
                    daexcel.Fill(dtexcel);
                }
                conn.Close();
            }
            catch (Exception ex)
            {
                Log.WriteLog("ReadExcel" + ex.Message);
                MessageBox.Show(ex.Message);

            }
            return dtexcel;
        }

to restoret he data without taking care of current db

USE [master]
ALTER DATABASE ForeSite_LS_s6 SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
RESTORE DATABASE ForeSite_LS_s6 FROM DISK = 'E:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Backup\ForeSite_LS_s6.bak'
WITH REPLACE
GO