Solved

How does one write Subroutines within top level routines in C#?

Posted on 2008-10-22
13
994 Views
Last Modified: 2013-12-17
I want to add a BackgroundWorker control to my code. So, I need my
bw_DoWork(object sender, DoWorkEventArgs e)
} <-- Line 57
} <-- Line 158
routine to be wrapped around other routines (between Code Lines 57 through 158), that I guess would then be called subroutines.
When I attempt this, I notice the word "void" in my other two routines (at the same level of the DoWork routine) have a squiggly line under them (i.e. my private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e) AND my "private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)" routines.
How do I need to write/structure this? Code below.
Many thanks,
Wallace
using System;

using System.Collections;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.IO;
 

namespace ParseLogErrors

{

    public partial class Form1 : Form

    {

        private System.Collections.Specialized.StringCollection folderCol;

       

        public Form1()

        {

            InitializeComponent();

            this.labelFileCountDisplay.Text = "";

            //this.lvwFilesAndFolders.ItemActivate += System.EventHandler(this.lvwFilesAndFolders_ItemActivate);

        }
 

        private void buttonParseLogs_Click(object sender, EventArgs e)

        {

            string dirName = textBoxSearchPath.Text;

                        

            // Set current working directory & verify it exists

            if (Directory.Exists(dirName))

            try

            {

                Directory.SetCurrentDirectory(dirName);

                MessageBox.Show(dirName);

            }

            catch (UnauthorizedAccessException)

            {

                MessageBox.Show("Not authorized to access " + dirName);

                return;

            }

            catch (FileNotFoundException)

            {

                MessageBox.Show("No such directory: " + dirName);

                return;

            }
 

        // Init ListView and folder collection

            folderCol = new System.Collections.Specialized.StringCollection();

            CreateHeadersAndFillListView();

            PaintListView(dirName);

            folderCol.Add(dirName);

            //PaintListView(@"c:\c# testing");

            //folderCol.Add(@"c:\c# testing");

            //PaintListView(@"\\crprdnsrc03\logs$\sd4\regional");

            //folderCol.Add(@"\\crprdnsrc03\logs$\sd4\regional");

        }
 

         private void bw_DoWork(object sender, DoWorkEventArgs e)

        {

        

        private void CreateHeadersAndFillListView()

        {

            ColumnHeader colHead;
 

            colHead = new ColumnHeader();

            colHead.Width = 500;

            colHead.Text = "Filename";

            this.lvwFilesAndFolders.GridLines = true;

            this.lvwFilesAndFolders.Columns.Add(colHead);
 

            colHead = new ColumnHeader();

            colHead.Width = 100;

            colHead.Text = "Size";

            this.lvwFilesAndFolders.GridLines = true;

            this.lvwFilesAndFolders.Columns.Add(colHead);
 

            colHead = new ColumnHeader();

            colHead.Width = 200;

            colHead.Text = "Last Accessed";

            this.lvwFilesAndFolders.GridLines = true;

            this.lvwFilesAndFolders.Columns.Add(colHead);

        }
 

        private void PaintListView(string root)

        {

            try

            {

                ListViewItem lvi;

                ListViewItem.ListViewSubItem lvsi;
 

                this.labelDisplayLogInfo.Text = root;

                DirectoryInfo dir = new DirectoryInfo(root);
 

                this.lvwFilesAndFolders.Items.Clear();
 

                DirectoryInfo[] dirs = dir.GetDirectories();

                FileInfo[] files = dir.GetFiles();
 

                this.lvwFilesAndFolders.BeginUpdate();
 

                foreach (System.IO.FileInfo fi in files)

                {

                    lvi = new ListViewItem();

                    lvi.Text = fi.Name;

                    //lvi.ImageIndex = 0;

                    lvi.Tag = fi.FullName;
 

                    lvsi = new ListViewItem.ListViewSubItem();

                    lvsi.Text = formatsizekb(fi.Length);

                    lvi.SubItems.Add(lvsi);
 

                    lvsi = new ListViewItem.ListViewSubItem();

                    lvsi.Text = fi.LastAccessTime.ToString();

                    lvi.SubItems.Add(lvsi);
 

                    this.lvwFilesAndFolders.Items.Add(lvi);
 

                    //Lets count the number of files

                    int file_count = 1;

                    foreach(FileInfo file in files)

                    {

                        this.labelFileCountDisplay.Text = Convert.ToString(file_count++);

                    }                                  

                }
 

                this.lvwFilesAndFolders.EndUpdate();

            }

            catch (System.Exception err)

            {

                MessageBox.Show("Error: " + err.Message);

            }
 

            this.lvwFilesAndFolders.View = View.Details;

        }

    

            private void lvwFilesAndFolders_ItemActive(object sender, System.EventArgs e)

        {

            ListView lvw = (ListView)sender;

            string filename = lvw.SelectedItems[0].Tag.ToString();

            Console.WriteLine(filename);

        }
 

        private void buttonExit_Click(object sender, EventArgs e)

        {

            this.Close();

        }
 

        //Formats File size

        private string formatsizekb(long lsize)

        {

            const int iKB = 1024;

            const long lMB = 1048576;
 

            if (lsize < iKB)

                return string.Format("{0:#,#} bytes", lsize);

            else if (lsize >= iKB && lsize < lMB) ;

                return string.Format("{0:#,#} KB", lsize / 1024);

        }

    }

        private void bw_DoWork(object sender, DoWorkEventArgs e)

        {
 
 

        }
 

        private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)

        {
 

        }
 

        private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)

        {
 

        }

                

    }

}

Open in new window

0
Comment
Question by:wally_davis
  • 8
  • 4
13 Comments
 

Expert Comment

by:malibuboats
Comment Utility
Remove the } on line 158.
0
 

Author Comment

by:wally_davis
Comment Utility
why would I do that? That's the ending brace for private void bw_DoWork(object sender, DoWorkEventArgs e)
{
}
This is the routine I want to wrap around all the other routines (that would be called subroutines, that is, if it can be done) in order to perform the thread work on all the routines within it. I'm trying to figure out how I can do this or do I have to re-write my code to do it another way?
0
 

Author Comment

by:wally_davis
Comment Utility
Additional information: I get a squggly line right after the line private void bw_DoWork(object sender, DoWorkEventArgs e)
{ <-- Squiggly appears here on line 58
/Code between Line 58 and Line 158 where the ending brace is for the DoWork routine.
The I get squigglys underneath the word "void" on Lines 165 and 170. (I've currently removed the Lines
159 through 163 so that the DoWork routine is not in my code twice).
0
 

Expert Comment

by:malibuboats
Comment Utility
Just for my clearification when the bw_DoWork method is fired you want it to also fire off the other methods you have listed between line 58 and 158?
0
 

Author Comment

by:wally_davis
Comment Utility
Correct
0
 

Assisted Solution

by:malibuboats
malibuboats earned 200 total points
Comment Utility
If that is the case you could just call those methods from the bw_DoWork method.  This will fire each of those methods when the bw_DoWork is called.
0
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

Author Comment

by:wally_davis
Comment Utility
sorry, I know the syntax for calling a subroutine in VB.Net (i.e. Call MySub() ), and I can't find anything on how to call a subroutine in C#. Could you show me the syntax please?
0
 

Expert Comment

by:malibuboats
Comment Utility
It looks like those methods are already being fired when the button click event is fired.  Lines 48 - 50.  The only thing that is not doing is closing the form, whic you can add at the end of the buton click event handler.
0
 

Author Comment

by:wally_davis
Comment Utility
right, so I can move these methods outside of the Click event and then call them. What is the syntax for calling other statements?
0
 

Author Comment

by:wally_davis
Comment Utility
There appears to be more challenges to the backgroundworker then first expected. I have controls that are loaded during some of these method routines and I'm getting an error "Error: Cross-thread operation not valid: Control 'lvwFilesAndFolders' access from a thread other than the thread it was created on".

This happens when the "private void PaintListView(string root)" method is called from the BackgroundWorker.DoWork Event,  and it has references to the ListView Control named "lvwFilesAndFolders".
How in the world do I get around this Cross-thread operation?
0
 
LVL 23

Accepted Solution

by:
Tiggerito earned 300 total points
Comment Utility
Worker threads are not allowed to directly alter Controls in Forms. You should use InvokeRequired and Invoke to get round this. Here's an example of the pattern normally used.
		protected void CallableFromWorker_Event(object sender, EventArgs e)

		{

			if (this.InvokeRequired)

			{

				this.Invoke(new EventHandler(this.CallableFromWorker_Event), new object[] {sender, e});

			}

			else

			{

				// can do GUI stuff safely here

			}

		}

Open in new window

0
 

Author Comment

by:wally_davis
Comment Utility
Tiggerito,
This was the final solution but you helped me tremendously so I'll aware you 300 points.
Malibuboats provided me with part of the other solution to actually use a Call within the DoWork Event handler. Thank you both.
0
 

Author Closing Comment

by:wally_davis
Comment Utility
Final solution ended up looking like this.
protected void bgw_DoWork(object sender, DoWorkEventArgs e)
        {            
            {
                this.Invoke(new MethodInvoker(delegate()
                {
                    progressBar1.PerformStep();

                    /* Lets call the other statements from here
                    to Perform Safe threading execution */
                    string dirName = textBoxSearchPath.Text;
                    folderCol = new System.Collections.Specialized.StringCollection();
                    PaintListView(dirName);
                    folderCol.Add(dirName);
                }));                                
            }                        
        }
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

A basic question.. “What is the Garbage Collector?” The usual answer given back: “Garbage collector is a background thread run by the CLR for freeing up the memory space used by the objects which are no longer used by the program.” I wondered …
In my previous article (http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_3.x/A_4362-Serialization-in-NET-1.html) we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now