Click here to Skip to main content
15,880,608 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,

I am trying to implement background worker and progreesbar in my code.But not working properly

My Code is as below.

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using Microsoft.Office.Interop.Excel;
using System.Diagnostics;
using System.Collections;
namespace CompareSuite
{
    public partial class Form1 : Form
    {
        //int lastrow1;
        Hashtable myHashtable;
        private bool _isDirty;
        public Form1()
        {
            InitializeComponent();
            _isDirty = true;
        }
        private void btnBrowse_Click(object sender, EventArgs e)
        {
            DialogResult resDialog = openFileDialog1.ShowDialog();
            if (resDialog.ToString() == "OK")
            {
                textBox1.Text = openFileDialog1.FileName;
            }
        }
        private void btnCompare_Click(object sender, EventArgs e)
        {
            if (textBox1.Text == "" | textBox2.Text == "")
            {
                MessageBox.Show("Comparing needs two files", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            else
            {
                try
                {
                    btnCompare.Enabled = false;
                    btnCompare.BackColor = SystemColors.Control;
                    btnCompare.ForeColor = SystemColors.Control;
                    toolStripProgressBar1.Visible = true;
                    backgroundWorker1.WorkerReportsProgress = true;
                    backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
                    backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
                    backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
                    backgroundWorker1.RunWorkerAsync();
         
                }
                catch(Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    
                }
            }
        }
        private void ExcelCompare()
        {
            CheckExcellProcesses();
            string path = textBox1.Text;
            string path1 = textBox2.Text;
            string Filename = path.Substring(path.LastIndexOf('\\') + 1);
            string Filename1 = path1.Substring(path.LastIndexOf('\\') + 1);
            string textpath = textBox1.Text.Substring(0, textBox1.Text.Length - Filename.Length);
            string fileloc = textpath + "New.MAS";
            Microsoft.Office.Interop.Excel.Application ExcelObj = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open(path, 0, true, 1, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
            //Microsoft.Office.Interop.Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open(path, 0, true, 0, "", "", "", "", "", "", "", 0, "", "", "");
            Microsoft.Office.Interop.Excel.Sheets sheets = theWorkbook.Worksheets;
            Microsoft.Office.Interop.Excel.Worksheet workSheet = (Microsoft.Office.Interop.Excel.Worksheet)sheets.get_Item(1);
            //Range last = workSheet.Cells.SpecialCells(XlCellType.xlCellTypeLastCell,Type.Missing);
            //Range wrange = workSheet.get_Range("A1",last);
            Range r1 = ((Microsoft.Office.Interop.Excel.Range)workSheet.Cells[1, 1]).EntireColumn;
            r1.Insert(XlInsertShiftDirection.xlShiftToRight, XlInsertFormatOrigin.xlFormatFromLeftOrAbove);
            Range r2 = (Microsoft.Office.Interop.Excel.Range)workSheet.Cells[1, 1];
            r2.Select();
            r2.FormulaR1C1 = "=LEFT(RC[1],100)";
            r2.Select();
            Range r3 = (Microsoft.Office.Interop.Excel.Range)workSheet.get_Range("A1", "A160237");
            r2.AutoFill(r3, XlAutoFillType.xlFillCopy);
            r3.Copy(Type.Missing);
            sheets.Add(Type.Missing, workSheet, 1, Microsoft.Office.Interop.Excel.XlSheetType.xlWorksheet);
            Microsoft.Office.Interop.Excel.Worksheet workSheetA = (Microsoft.Office.Interop.Excel.Worksheet)sheets.get_Item(2);
            Range r4 = (Microsoft.Office.Interop.Excel.Range)workSheetA.Cells[1, 1];
            r4.PasteSpecial(XlPasteType.xlPasteValues, XlPasteSpecialOperation.xlPasteSpecialOperationNone, Type.Missing, Type.Missing);
            ExcelObj.CutCopyMode = XlCutCopyMode.xlCopy;
            r4 = ((Microsoft.Office.Interop.Excel.Range)workSheetA.Cells[1, 1]).EntireColumn;
            r4.Select();
            r4.TextToColumns(r4, XlTextParsingType.xlDelimited, XlTextQualifier.xlTextQualifierNone, false, true, false, false, false, true, "|", Type.Missing, Type.Missing, Type.Missing, true);
            Range r5 = ((Microsoft.Office.Interop.Excel.Range)workSheetA.Cells[1, 3]).EntireColumn;
            r5.Copy(Type.Missing);
            workSheet.Select(Type.Missing);
            Range o = (Microsoft.Office.Interop.Excel.Range)workSheet.Cells[1, 1];
            o.PasteSpecial(XlPasteType.xlPasteValues, XlPasteSpecialOperation.xlPasteSpecialOperationNone, Type.Missing, Type.Missing);
            ExcelObj.CutCopyMode = XlCutCopyMode.xlCopy;
            Range data = (Microsoft.Office.Interop.Excel.Range)workSheet.get_Range("A1", "B1").EntireColumn;
            theWorkbook.Names.Add("data", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, "=" + Filename + "!C1:C2", Type.Missing);
            workSheetA.Select(Type.Missing);
            r5.Copy(Type.Missing);
            Microsoft.Office.Interop.Excel.Application ExcelObj1 = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Workbook theWorkbook1 = ExcelObj1.Workbooks.Open(path1, 0, true, 1, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
            Microsoft.Office.Interop.Excel.Sheets sheets1 = theWorkbook1.Worksheets;
            Microsoft.Office.Interop.Excel.Worksheet workSheet1 = (Microsoft.Office.Interop.Excel.Worksheet)sheets1.get_Item(1);
            sheets1.Add(Type.Missing, workSheet1, 1, Microsoft.Office.Interop.Excel.XlSheetType.xlWorksheet);
            Microsoft.Office.Interop.Excel.Worksheet workSheet1A = (Microsoft.Office.Interop.Excel.Worksheet)sheets1.get_Item(2);
            Range r6 = (Microsoft.Office.Interop.Excel.Range)workSheet1A.Cells[1, 1];
            r6.PasteSpecial(XlPasteType.xlPasteValues, XlPasteSpecialOperation.xlPasteSpecialOperationNone, Type.Missing, Type.Missing);
            Range r7 = ((Microsoft.Office.Interop.Excel.Range)workSheet1.Cells[1, 1]).EntireColumn;
            r7.Insert(XlInsertShiftDirection.xlShiftToRight, XlInsertFormatOrigin.xlFormatFromLeftOrAbove);
            Range r8 = (Microsoft.Office.Interop.Excel.Range)workSheet1.Cells[1, 1];
            //r8.Select();
            r8.FormulaR1C1 = "=LEFT(RC[1],100)";
            //r8.Select();
            Range r9 = (Microsoft.Office.Interop.Excel.Range)workSheet1.get_Range("A1", "A160237");
            r8.AutoFill(r9, XlAutoFillType.xlFillCopy);
            r9.Copy(Type.Missing);
            sheets1.Add(Type.Missing, workSheet1A, 1, Microsoft.Office.Interop.Excel.XlSheetType.xlWorksheet);
            Microsoft.Office.Interop.Excel.Worksheet workSheet1B = (Microsoft.Office.Interop.Excel.Worksheet)sheets1.get_Item(3);
            Range r10 = (Microsoft.Office.Interop.Excel.Range)workSheet1B.Cells[1, 1];
            r10.PasteSpecial(XlPasteType.xlPasteValues, XlPasteSpecialOperation.xlPasteSpecialOperationNone, Type.Missing, Type.Missing);
            ExcelObj1.CutCopyMode = XlCutCopyMode.xlCopy;
            r10 = ((Microsoft.Office.Interop.Excel.Range)workSheet1B.Cells[1, 1]).EntireColumn;
            r10.Select();
            r10.TextToColumns(r10, XlTextParsingType.xlDelimited, XlTextQualifier.xlTextQualifierNone, false, true, false, false, false, true, "|", Type.Missing, Type.Missing, Type.Missing, true);
            Range r11 = ((Microsoft.Office.Interop.Excel.Range)workSheet1B.Cells[1, 3]).EntireColumn;
            r11.Copy(Type.Missing);
            Range r12 = ((Microsoft.Office.Interop.Excel.Range)workSheet1.Cells[1, 1]).EntireColumn;
            r12.PasteSpecial(XlPasteType.xlPasteValues, XlPasteSpecialOperation.xlPasteSpecialOperationNone, Type.Missing, Type.Missing);
            //theWorkbook1.SaveAs("D:\\MAS\\Rameel.xlsx", XlFileFormat.xlXMLSpreadsheet, Type.Missing, Type.Missing, false, false, XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            //theWorkbook1.SaveCopyAs("D:\\MAS\\rameel.xlsx");
            //ExcelObj1.Save("D:\MAS\rameel.xls");
            ExcelObj1.CutCopyMode = XlCutCopyMode.xlCopy;
            Range data1 = (Microsoft.Office.Interop.Excel.Range)workSheet1.get_Range("A1", "B1").EntireColumn;
            //r13.Select();
            theWorkbook1.Names.Add("data1", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, "=" + Filename1 + "!C1:C2", Type.Missing);
            workSheet1A.Select(Type.Missing);
            r6.Select();
            r6.EntireColumn.ColumnWidth = 17.43;
            Range r14 = (Microsoft.Office.Interop.Excel.Range)workSheet1A.Cells[1, 2];
            r14.Select();
            r14.FormulaR1C1 = "=VLOOKUP(RC[-1],data1,2,FALSE)";
            Range last1 = ((Microsoft.Office.Interop.Excel.Range)workSheet1A.Cells[1, 1]).SpecialCells(XlCellType.xlCellTypeLastCell, Type.Missing);
            Range R15 = workSheet1A.get_Range("B1", last1);
            r14.AutoFill(R15, XlAutoFillType.xlFillCopy);
            r14.EntireColumn.Select();
            //ro.Insert(XlInsertShiftDirection.xlShiftDown, XlInsertFormatOrigin.xlFormatFromLeftOrAbove);
            r14.AutoFilter(2, Type.Missing, XlAutoFilterOperator.xlOr, "#N/A", Type.Missing);
            Range ro = (Microsoft.Office.Interop.Excel.Range)workSheet1A.Cells[1,2];
            ro.Select();
            if ((string)ro.Text!="#N/A")
            {
                MessageBox.Show("No new items available");
                KillExcel();
                toolStripProgressBar1.Value = 0;
                toolStripProgressBar1.Visible = false;
                return;
            }
            //r6.Select();
            r6.EntireColumn.Select();
            r6.EntireColumn.Copy(Type.Missing);
            sheets.Add(Type.Missing, workSheetA, 1, Microsoft.Office.Interop.Excel.XlSheetType.xlWorksheet);
            Microsoft.Office.Interop.Excel.Worksheet workSheetB = (Microsoft.Office.Interop.Excel.Worksheet)sheets.get_Item(3);
            Range r17 = ((Microsoft.Office.Interop.Excel.Range)workSheetB.Cells[1, 1]);
            r17.ColumnWidth = 26.71;
            r17.PasteSpecial(XlPasteType.xlPasteValues, XlPasteSpecialOperation.xlPasteSpecialOperationNone, Type.Missing, Type.Missing);
            ExcelObj.CutCopyMode = XlCutCopyMode.xlCopy;
            Range r16 = (Microsoft.Office.Interop.Excel.Range)workSheetB.Cells[1, 2];
            r16.Select();
            r16.FormulaR1C1 = "=VLOOKUP(RC[-1],data,2,FALSE)";
            Range last = ((Microsoft.Office.Interop.Excel.Range)workSheetB.Cells[1, 1]).SpecialCells(XlCellType.xlCellTypeLastCell, Type.Missing);
            Range r18 = workSheetB.get_Range("B1", last);
            r16.AutoFill(r18, XlAutoFillType.xlFillCopy);
            r16.EntireColumn.Copy(Type.Missing);
            FileStream fs = null;
            if (!File.Exists(fileloc))
            {
                using (fs = File.Create(fileloc))
                {
                }
                System.IO.File.WriteAllText(fileloc, Clipboard.GetText());
            }
            ExcelObj.CutCopyMode = XlCutCopyMode.xlCopy;
            theWorkbook.Close(false, Type.Missing, false);
            theWorkbook1.Close(false, Type.Missing, false);
            ExcelObj.Quit();
            ExcelObj1.Quit();
            KillExcel();
            //lastrow1 = workSheet.UsedRange.Rows.Count;
            //theWorkbook.SaveAs(path + @"\XMLCopy.xlsx", Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel12,"","",true,"", Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,"","","","");
        }
        private void CheckExcellProcesses()
        {
            Process[] AllProcesses = Process.GetProcessesByName("excel");
            myHashtable = new Hashtable();
            int iCount = 0;
            foreach (Process ExcelProcess in AllProcesses)
            {
                myHashtable.Add(ExcelProcess.Id, iCount);
                iCount = iCount + 1;
            }
        }
        private void KillExcel()
        {
            Process[] AllProcesses = Process.GetProcessesByName("excel");
            // check to kill the right process
            foreach (Process ExcelProcess in AllProcesses)
            {
                if (myHashtable.ContainsKey(ExcelProcess.Id) == false)
                    ExcelProcess.Kill();
            }
            AllProcesses = null;
        }
        private void btnBrowse2_Click(object sender, EventArgs e)
        {
            DialogResult resDialog = openFileDialog2.ShowDialog();
            if (resDialog.ToString() == "OK")
            {
                textBox2.Text = openFileDialog2.FileName;
            }
        }
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_isDirty)
            {
                if (DialogResult.Yes != MessageBox.Show(
                    "Close the application?",
                    "Warning!!!!",
                     MessageBoxButtons.YesNo,
                     MessageBoxIcon.Warning,
                     MessageBoxDefaultButton.Button2))
                {
                    e.Cancel = true;
                }
            }
        }
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            //backgroundWorker1.ReportProgress(10);
            //Thread.Sleep(164);
            //backgroundWorker1.ReportProgress(20);
            //Thread.Sleep(164);
            //backgroundWorker1.ReportProgress(30);
            //Thread.Sleep(164);
            //backgroundWorker1.ReportProgress(40);
            //Thread.Sleep(164);
            //backgroundWorker1.ReportProgress(50);
            //Thread.Sleep(164);
            //backgroundWorker1.ReportProgress(70);
            //Thread.Sleep(164);
            //backgroundWorker1.ReportProgress(95);
            //Thread.Sleep(164);
            //backgroundWorker1.ReportProgress(100);
            CountTheTime();
        }
        private void CountTheTime()
        { 
            int initialValue = 100; 
            for (int count = 0; count < initialValue; count = count + 2)
             {
                 Thread.Sleep(100);
                 backgroundWorker1.ReportProgress(count); 
             }
        }
        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            toolStripProgressBar1.Value = e.ProgressPercentage;
        }
        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            ExcelCompare();
            textBox1.Text = "";
            textBox2.Text = "";
            btnCompare.Enabled = true;
            btnCompare.BackColor = Color.LightSkyBlue;
            btnCompare.ForeColor = Color.Black;
            toolStripProgressBar1.Value = 0;
            toolStripProgressBar1.Visible = false;
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            toolStripProgressBar1.Visible = false;
        }

       
    }
}


Please help!!!!
Posted
Updated 4-May-11 4:10am
v2
Comments
yesotaso 4-May-11 10:53am    
Nice work with excel :)
BobJanova 4-May-11 11:04am    
Define 'not working properly'.

Also, the Excel code is irrelevant to your problem.

In your ProgressChanged event, you have to use a delegate to update the ProgressBar control.

C#
public void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    MethodInvoker involker = delegate 
    { 
        tooltipProgressBar1.Value = e.ProgressPercentage; 
    };     
    tooltipProgressBar1.BeginInvoke(invoker); 
}


You really didn't need to post all theat source code, either. It just cluttered your question.
 
Share this answer
 
Comments
Olivier Levrey 4-May-11 10:54am    
This is not correct. You don't need to use Invoke or BeginInvoke in the ProgressChanged handler: the BackgroundWorker class does it for you.
Have a look to this link: http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.progresschanged.aspx
#realJSOP 4-May-11 10:59am    
Sometimes it doesn't work. I've personally had to do this before, so he might want to try it to see.
Olivier Levrey 4-May-11 11:06am    
Mmmm probably because the worker was created from a different thread then.
Anyway OP can always try this, it won't hurt.
Rick Shaub 4-May-11 15:15pm    
It's good practice anyway. Even better to check if invoke is required and only invoke when required. Although, with UI code it's rarely a noticable improvement.
DaveyM69 4-May-11 16:05pm    
This can only happen if the RunWorkerAsync is called from a non UI thread or called before the SynchronizationContext is set (normally happens when calling from a form's constructor - the Load event and beyond are fine) as an AsyncOperation is created which handles Post/PostOperationCompleted to the UI thread via the SynchronizationContext.
It should work.
Did you use the debugger to make sure your worker starts? Do you enter the DoWork handler?
Is your progress bar "normal"? For example make sure the range of your progress bar is valid.
And I see that you are using toolStripProgressBar. You should try with a normal ProgressBar just to check.

Check out these links:
ProgressWorker[^]
ProgressForm: A simple form linked to a BackgroundWorker[^]
 
Share this answer
 
v2
I took your code and ran it as a sample. It works perfectly for me, which leads me to wonder if the problem that you are having is that btnCompare isn't mapped to btnCompare_Click. Put a breakpoint inside this method and see if it hits it.
 
Share this answer
 
v2
Comments
#realJSOP 4-May-11 13:51pm    
There ya go, thinking he knows how to use the tools at hand... Silly rabbit.
Pete O'Hanlon 4-May-11 14:21pm    
It's my warped sense of humour.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900