Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

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

Posted on 2008-10-22
13
Medium Priority
?
1,000 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 8
  • 4
13 Comments
 

Expert Comment

by:malibuboats
ID: 22778791
Remove the } on line 158.
0
 

Author Comment

by:wally_davis
ID: 22778934
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
ID: 22779025
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
NEW Veeam Agent for Microsoft Windows

Backup and recover physical and cloud-based servers and workstations, as well as endpoint devices that belong to remote users. Avoid downtime and data loss quickly and easily for Windows-based physical or public cloud-based workloads!

 

Expert Comment

by:malibuboats
ID: 22779324
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
ID: 22779786
Correct
0
 

Assisted Solution

by:malibuboats
malibuboats earned 600 total points
ID: 22780364
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
 

Author Comment

by:wally_davis
ID: 22780748
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
ID: 22780890
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
ID: 22780970
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
ID: 22782022
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:
Tony McCreath earned 900 total points
ID: 22784629
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
ID: 22790309
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
ID: 31509410
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

Learn Veeam advantages over legacy backup

Every day, more and more legacy backup customers switch to Veeam. Technologies designed for the client-server era cannot restore any IT service running in the hybrid cloud within seconds. Learn top Veeam advantages over legacy backup and get Veeam for the price of your renewal

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…
In this video, Percona Director of Solution Engineering Jon Tobin discusses the function and features of Percona Server for MongoDB. How Percona can help Percona can help you determine if Percona Server for MongoDB is the right solution for …

715 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