Avatar of tia_kamakshi
tia_kamakshiFlag for United Arab Emirates

asked on 

Background worker in Widows Application

Hi,

I am working on Windows Application in ASP.net2.0 and C#

This application has to find and replace text in particular folder.

If my folder is big than my system hangs. So I am using BackgroundWorker of .Net2.0

Now when I reach in _DoWork  method of the BackgroundWorker then I call the class MyWorkerClass

void bgWorker_DoWork(object sender, DoWorkEventArgs e)
 {
      WorkInfo info = (WorkInfo)e.Argument;
      MyWorkerClass m = new MyWorkerClass(info,bgWorker, this);
      e.Result = m.DoReplaceText();
 }

then in class MyWorkerClass, Here I am in Debug mode and my system is not going after the point

 BackgroundWorker bgWorker = null;
 
 Can anyone help me in this, that what is the problem in my code.
 
 My code has to update progress bar and the file processed count on the screen regularly.
 
 I am pasting my code as well.  
 
 Many Thanks
 
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
 
namespace BackGroundWorkerSample
{
    public partial class frmBackGroundWorker : Form
    {
        public frmBackGroundWorker()
        {
            InitializeComponent();
        }
 
        BackgroundWorker bgWorker = new BackgroundWorker();
        private void btnStart_Click(object sender, EventArgs e)
        {
            string strFind = txtFind.Text;
            string strReplace = txtReplace.Text;
 
            string folderPath = txtFolderPath.Text;
            string SearchInFiles = txtSearchInFiles.Text;
            
            UseWaitCursor = true;
            btnStart.Enabled = false;
 
            
 
            bgWorker.RunWorkerAsync(new WorkInfo(strFind, strReplace, folderPath, SearchInFiles, this));
        }
 
        private void Form1_Load(object sender, EventArgs e)
        {
            bgWorker.WorkerReportsProgress = true;
            bgWorker.WorkerSupportsCancellation = true;
            bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);
            bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWorker_RunWorkerCompleted);
            bgWorker.ProgressChanged += new ProgressChangedEventHandler(bgWorker_ProgressChanged);
        }
 
        void bgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            workerProgress.Value = e.ProgressPercentage;            
        }
 
        void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            int[] myResult = (int[]) e.Result;
            foreach (int i in myResult)
                txtResult.Text += i.ToString() + " ";
 
            btnStart.Enabled = true;
            UseWaitCursor = false;
        }
 
        void bgWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            WorkInfo info = (WorkInfo)e.Argument;
            MyWorkerClass m = new MyWorkerClass(info,bgWorker, this);
            e.Result = m.DoReplaceText();
        }
 
        private void btnStop_Click(object sender, EventArgs e)
        {
            bgWorker.CancelAsync();
            UseWaitCursor = false;
            btnStart.Enabled = true;
        }
 
        public void updateScreenControls(string strFileProcessedCount)
        {
            ttlFileProcessedCount.Text = strFileProcessedCount;
        }
    }
}
 
 
 
 
 
 
 
 
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.ComponentModel;
using System.IO;
 
namespace BackGroundWorkerSample
{
    public class MyWorkerClass
    {
        BackgroundWorker bgWorker = null;
        public string Find;
        public string Replace;
        public string FolderPath;
        public string SearchInFiles;
        public frmBackGroundWorker FrmBackGroundWorker;
 
        public MyWorkerClass(WorkInfo info, BackgroundWorker bw, frmBackGroundWorker frmBackGroundWorker)
        {
            this.Find = info.Find;
            this.Replace = info.Replace;
            this.FolderPath = info.FolderPath;
            this.SearchInFiles = info.SearchInFiles;            
            this.bgWorker = bw;
 
            this.FrmBackGroundWorker = info.FrmBackGroundWorker;
        }
 
 
        public bool ReplaceText(ref string content, string oldValue, string newValue, ref int replaced)
        {
 
            Boolean isReplaced = false;
            int startIndex = 0;
 
            while (startIndex != -1)
            {
                startIndex = content.IndexOf(oldValue, startIndex);
                if (startIndex != -1)
                {
                    content = content.Remove(startIndex, oldValue.Length);
                    content = content.Insert(startIndex, newValue);
                    replaced += 1;
                    isReplaced = true;
                }
            }
            return isReplaced;
        }
 
 
        public string DoReplaceText()
        {
            int replaced = 0;
            int fileProcessed = 0;
            int i = 0;
 
            string strFind = this.Find;
            string strReplace= this.Replace;
            string strFolderPath = this.FolderPath;
            string strSearchInFiles = this.SearchInFiles;
 
            //Get all the files from the root directory filtered by a filter text.
            string[] fileList = Directory.GetFiles(@"" + strFolderPath, strSearchInFiles, SearchOption.AllDirectories);
 
            //Loop through each file, call the ReplaceText() method
            //and replace the file if something was replaced.
            foreach (string file in fileList)
            {
                i = i + 1;
                StreamReader sr = new StreamReader(file);
                string content = sr.ReadToEnd();
                sr.Close();
                sr.Dispose();
 
                if (ReplaceText(ref content, strFind, strReplace, ref replaced))
                {
                    StreamWriter sw = new StreamWriter(file);
                    sw.Write(content);
                    sw.Flush();
                    sw.Close();
                    sw.Dispose();
                }
 
                if (bgWorker.CancellationPending)
                    break;
 
                //numbers.Add(i + (i + 1));
                System.Threading.Thread.Sleep(15);
 
                // Raise the ProgressChanged event and set the current progress value
                bgWorker.ReportProgress((int)i);
 
                fileProcessed = fileProcessed + 1;
                //ttlFileProcessedCount
                FrmBackGroundWorker.updateScreenControls(fileProcessed.ToString());
            }
 
            return "Total replacements = " + replaced + "" + " from files " + fileProcessed;            
        }
    }
 
    public class WorkInfo
    {
        public string Find;
        public string Replace;
        public string FolderPath;
        public string SearchInFiles;
        public frmBackGroundWorker FrmBackGroundWorker;
 
        public WorkInfo(string strFind, string strReplace, string strFolderPath, string strSearchInFiles, frmBackGroundWorker ffrmBackGroundWorker)
        {
            this.Find = strFind;
            this.Replace = strReplace;
            this.FolderPath = strFolderPath;
            this.SearchInFiles = strSearchInFiles;
            this.FrmBackGroundWorker = ffrmBackGroundWorker;
        }
 
    }
}

Open in new window

.NET ProgrammingC#

Avatar of undefined
Last Comment
tia_kamakshi
Avatar of Mike Tomlinson
Mike Tomlinson
Flag of United States of America image

Why are you making a seperate class called MyWorkerClass?  You've "tightly coupled" it to your original form requiring an instance of it to be passed in.  This makes it basically unreuseable by other forms thus negating any benefit of seperating it from the form...

Why not put all that code into the form itself?  There will be less hassle since you won't have to pass all that info around...
Avatar of Joel Coehoorn
Joel Coehoorn
Flag of United States of America image

@Idle_Mind: It looks like he's actually passing TWO references to the form.  One in the WorkInfo struct and one as a parameter directly.  It looks like the only place he uses either reference is a call to .updateScreenControls().  Just get rid of the form reference and move that call to the bgWorker_ProgressChanged() method and he has good separation again.


> "I am working on Windows Application in ASP.net2.0 and C# "

Either you are using ASP.Net or your are building a Windows app.  ASP.Net is for web pages, which can be seen from browsers on operating systems other than windows.  You are not building a web page, and therefore are not using ASP.Net.

> "my system is not going after the point   BackgroundWorker bgWorker = null;"

Me:  Doctor, it hurts when I do this.
Doctor:  Then don't do that.

I would tell you to just remove that line, but I can't find it in the code you posted.


Avatar of tia_kamakshi
tia_kamakshi
Flag of United Arab Emirates image

ASKER

Hi,

Thanks for your reply.

>> It looks like he's actually passing TWO references to the form.

Where is it. Where I am passing TWO references to the form??

When I have commented line, where it was hanging and as you have suggested.

Now I get the error

Error      1      'BackGroundWorkerSample.MyWorkerClass' does not contain a definition for 'bgWorker'
Error      2      The name 'bgWorker' does not exist in the current context
Error      3      The name 'bgWorker' does not exist in the current context


If you scroll down in my code there is a class MyWorkerClass, this is the code.

Please ask me if you have any more doubts

Thanks


using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.ComponentModel;
using System.IO;

namespace BackGroundWorkerSample
{
    public class MyWorkerClass
    {
    // This is the line I am talking about. Is when the Application runs in the background, then it does not come to the debugger. IS IT??
        BackgroundWorker bgWorker = null;
       
       
        public string Find;
        public string Replace;
        public string FolderPath;
        public string SearchInFiles;
        public frmBackGroundWorker FrmBackGroundWorker;
Avatar of Joel Coehoorn
Joel Coehoorn
Flag of United States of America image

Okay, I see where that line is now (line 98 in your posted snippet).  As I said, I couldn't find it before.  Go ahead and uncomment it for now.  Now for the two form references:

First, let's look at this line (#32):
        bgWorker.RunWorkerAsync(new WorkInfo(strFind, strReplace, folderPath, SearchInFiles, this));

Easy enough to understand.  The last parameter to your WorkInfo struct is a reference to the current form.  That's the first reference.  This line will cause the bgWorker_DoWork() method to be called.  Looking at that method, you have this line:
            MyWorkerClass m = new MyWorkerClass(info,bgWorker, this);

Here we see you pass your WorkInfo struct, which already contains a reference to the form, and the this pointer, which is a _2nd_ reference to the form.

Avatar of tia_kamakshi
tia_kamakshi
Flag of United Arab Emirates image

ASKER

Yeah! Thanks I found the double reference. I have fixed it. And I am gone bit ahead...

As I have already mentioned that my this method is only to replace the text from the files in the Directories and subdirectories

Now I am stopped at method ReplaceText

when I debug line by line I am trapped in the loop and looks working fine as it is replacing the text and count increases

When I click run to cursor at line return isReplaced;

I wait for a long but the debugger is not comming. In the first file there is only 516 lines from where text need to be repleced.

May be this is the reason my count and progressbar on the screen in not updated.

What is the problem here?

Also where I have to set max value of progress bar, If you can help me in this context as well

It will be very nice of you.

My count on screen is updated from the method

FrmBackGroundWorker.updateScreenControls(fileProcessed.ToString());


Many Thanks again for your coperation

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
 
namespace BackGroundWorkerSample
{
    public partial class frmBackGroundWorker : Form
    {
        public frmBackGroundWorker()
        {
            InitializeComponent();
        }
 
        BackgroundWorker bgWorker = new BackgroundWorker();
        private void btnStart_Click(object sender, EventArgs e)
        {
            string strFind = txtFind.Text;
            string strReplace = txtReplace.Text;
 
            string folderPath = txtFolderPath.Text;
            string SearchInFiles = txtSearchInFiles.Text;
            
            UseWaitCursor = true;
            btnStart.Enabled = false;
 
            
 
            bgWorker.RunWorkerAsync(new WorkInfo(strFind, strReplace, folderPath, SearchInFiles, this));
        }
 
        private void Form1_Load(object sender, EventArgs e)
        {
            bgWorker.WorkerReportsProgress = true;
            bgWorker.WorkerSupportsCancellation = true;
            bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);
            bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWorker_RunWorkerCompleted);
            bgWorker.ProgressChanged += new ProgressChangedEventHandler(bgWorker_ProgressChanged);
        }
 
        void bgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            workerProgress.Value = e.ProgressPercentage;            
        }
 
        void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            int[] myResult = (int[]) e.Result;
            foreach (int i in myResult)
                txtResult.Text += i.ToString() + " ";
 
            btnStart.Enabled = true;
            UseWaitCursor = false;
        }
 
        void bgWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            WorkInfo info = (WorkInfo)e.Argument;
            MyWorkerClass m = new MyWorkerClass(info,bgWorker);
            e.Result = m.DoReplaceText();
        }
 
        private void btnStop_Click(object sender, EventArgs e)
        {
            bgWorker.CancelAsync();
            UseWaitCursor = false;
            btnStart.Enabled = true;
        }
 
        public void updateScreenControls(string strFileProcessedCount)
        {
            ttlFileProcessedCount.Text = strFileProcessedCount;
            Application.DoEvents();
 
        }
    }
}
 
 
 
 
 
 
 
 
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.ComponentModel;
using System.IO;
 
namespace BackGroundWorkerSample
{
    public class MyWorkerClass
    {
        BackgroundWorker bgWorker = null;
        public string Find;
        public string Replace;
        public string FolderPath;
        public string SearchInFiles;
        public frmBackGroundWorker FrmBackGroundWorker;
 
        public MyWorkerClass(WorkInfo info, BackgroundWorker bw)
        {
            this.Find = info.Find;
            this.Replace = info.Replace;
            this.FolderPath = info.FolderPath;
            this.SearchInFiles = info.SearchInFiles;            
            this.bgWorker = bw;
 
            this.FrmBackGroundWorker = info.FrmBackGroundWorker;
        }
 
 
        public bool ReplaceText(ref string content, string oldValue, string newValue, ref int replaced)
        {
 
            Boolean isReplaced = false;
            int startIndex = 0;
 
            while (startIndex != -1)
            {
                startIndex = content.IndexOf(oldValue, startIndex);
                if (startIndex != -1)
                {
                    content = content.Remove(startIndex, oldValue.Length);
                    content = content.Insert(startIndex, newValue);
                    replaced += 1;                    
                    isReplaced = true;
                    
                }
            }
            return isReplaced;
        }
 
 
        public string DoReplaceText()
        {
            int replaced = 0;
            int fileProcessed = 0;
            int i = 0;
 
            string strFind = this.Find;
            string strReplace= this.Replace;
            string strFolderPath = this.FolderPath;
            string strSearchInFiles = this.SearchInFiles;
 
            //Get all the files from the root directory filtered by a filter text.
            string[] fileList = Directory.GetFiles(@"" + strFolderPath, strSearchInFiles, SearchOption.AllDirectories);
 
            //Loop through each file, call the ReplaceText() method
            //and replace the file if something was replaced.
            foreach (string file in fileList)
            {
                i = i + 1;
                StreamReader sr = new StreamReader(file);
                string content = sr.ReadToEnd();
                sr.Close();
                sr.Dispose();
 
                if (ReplaceText(ref content, strFind, strReplace, ref replaced))
                {
                    StreamWriter sw = new StreamWriter(file);
                    sw.Write(content);
                    sw.Flush();
                    sw.Close();
                    sw.Dispose();
                }
 
                if (bgWorker.CancellationPending)
                    break;
 
                //numbers.Add(i + (i + 1));
                System.Threading.Thread.Sleep(15);
 
                // Raise the ProgressChanged event and set the current progress value
                bgWorker.ReportProgress((int)i);
 
                fileProcessed = fileProcessed + 1;
                //ttlFileProcessedCount
                FrmBackGroundWorker.updateScreenControls(fileProcessed.ToString());
            }
 
            return "Total replacements = " + replaced + "" + " from files " + fileProcessed;            
        }
    }
 
    public class WorkInfo
    {
        public string Find;
        public string Replace;
        public string FolderPath;
        public string SearchInFiles;
        public frmBackGroundWorker FrmBackGroundWorker;
 
        public WorkInfo(string strFind, string strReplace, string strFolderPath, string strSearchInFiles, frmBackGroundWorker ffrmBackGroundWorker)
        {
            this.Find = strFind;
            this.Replace = strReplace;
            this.FolderPath = strFolderPath;
            this.SearchInFiles = strSearchInFiles;
            this.FrmBackGroundWorker = ffrmBackGroundWorker;
        }
 
    }
}

Open in new window

Avatar of Joel Coehoorn
Joel Coehoorn
Flag of United States of America image

Add this on line 134 right after isReplaced = true;
Avatar of tia_kamakshi
tia_kamakshi
Flag of United Arab Emirates image

ASKER

Many Thanks I will come to you.
Avatar of tia_kamakshi
tia_kamakshi
Flag of United Arab Emirates image

ASKER

HI,

I have tried writting this to the place you suggested.

I get the error:

Error      1      'BackGroundWorkerSample.MyWorkerClass' does not contain a definition for 'isReplaced'      


My changed code as you suggested is as below.

Awaiting your reply

Thanks

public bool ReplaceText(ref string content, string oldValue, string newValue, ref int replaced)
        {

            Boolean isReplaced = false;
            int startIndex = 0;

            while (startIndex != -1)
            {
                startIndex = content.IndexOf(oldValue, startIndex);
                if (startIndex != -1)
                {
                    content = content.Remove(startIndex, oldValue.Length);
                    content = content.Insert(startIndex, newValue);
                    replaced += 1;
                    this.isReplaced = true;
                }
            }
            return isReplaced;
        }
ASKER CERTIFIED SOLUTION
Avatar of Joel Coehoorn
Joel Coehoorn
Flag of United States of America image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of tia_kamakshi
tia_kamakshi
Flag of United Arab Emirates image

ASKER

Thanks for your reply.

It works. But now I am getting error

"Cross-thread operation not valid:"

I have posted my question here, if you can help me there as well
https://www.experts-exchange.com/questions/23581234/Cross-thread-operation-not-valid.html

I think my this question is resolved.

Many thanks for your co-operation
.NET Programming
.NET Programming

The .NET Framework is not specific to any one programming language; rather, it includes a library of functions that allows developers to rapidly build applications. Several supported languages include C#, VB.NET, C++ or ASP.NET.

137K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo