Listing the methods in a .cs class listing

ddanbe 0 Tallied Votes 419 Views Share

For a small class it doesn’t matter that much, but for a bigger class I find it handy to have an oversight of all the methods at hand. That’s what I did here. One requirement is that the class file has already been compiled error free. Don’t know if my algo to detect a “method” line is bullet proof, but it works in most if not all cases tested. Tips on how this could be improved are always welcome.
Further highlights:
How to: Show text in a listbox.
How to: Save text in a file
How to: Open and read a text file into a List<string>
How to: Use of page preview
How to: Print text

Just started a new form application, added a ListBox and 4 buttons and a OpenFileDialog.
This is how my design looks,
MList.png
the rest should be obvious from the code. Enjoy!

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Printing;

namespace MethodExtractor
{
    public partial class MainWindow : Form
    {
        private string[] startStrs = new string[] { "public", "private", "protected", "internal" };
        private List<string> Methods = new List<string>();
        private string FName = string.Empty;
        private PrintDocument PrintDoc;
        private SaveFileDialog saveFile_Dlg;
        private Font printFont = new Font("Times New Roman", 12);

        public MainWindow()
        {
            InitializeComponent();
            saveFile_Dlg = new SaveFileDialog();
            //Create a PrintDocument object
            PrintDoc = new PrintDocument();
            //Add PrintPage event handler to the document to print
            PrintDoc.PrintPage += new PrintPageEventHandler(printAPage);
        }

        /// <summary>
        /// str is assumed to be trimmed
        /// </summary>
        /// <param name="str"></param>
        /// <param name="startStrs">the strings were str has to start with to return true</param>
        /// <returns></returns>
        private bool OKtoProcess(string str, string[] startStrs)
        {
            foreach(string item in startStrs)
            {
                if (str.StartsWith(item))
                {
                    return true;
                }
            }
            return false;
        }

        private void OpenFileBtn_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                listBox1.Items.Clear(); 
                FName = openFileDialog1.SafeFileName; //just the name, not the whole path
                StreamReader reader = new StreamReader(openFileDialog1.FileName);
                string line = String.Empty;
                string writeStr = String.Empty;
                int indx = 0;
                while ((line = reader.ReadLine()) != null)
                {
                    line = line.TrimStart(new char[] { ' ', '\t' });
                    if (OKtoProcess(line, startStrs))
                    {
                        indx = line.IndexOf(')');
                        if (indx != -1)
                        {
                            writeStr = line.Substring(0, indx + 1);
                            Methods.Add(writeStr);
                            listBox1.Items.Add(writeStr);
                        }
                    }
                }
                reader.Close();
            }
        }

        private void SaveListBtn_Click(object sender, EventArgs e)
        {
            saveFile_Dlg.Filter = "C sharp file|*.cs| Text file|*.txt";
            saveFile_Dlg.Title = "Save a method list";
            saveFile_Dlg.ShowDialog();
            if (saveFile_Dlg.ShowDialog() == DialogResult.OK)
            {
                bool append = true;
                string fullPath = saveFile_Dlg.FileName;
                StreamWriter writer = new StreamWriter(fullPath, append);
                for (int i = 0; i < listBox1.Items.Count; i++)
			    {
                    writer.WriteLine(listBox1.Items[i]);
			    }
                writer.Close();               
            }           
        }

        // Called by the Print method, print some tekst lines from a list
        private void printAPage(object sender, PrintPageEventArgs PE)
        {
            int count = 1;
            float yPos = 0f;
            float leftMargin = PE.MarginBounds.Left;
            float topMargin = PE.MarginBounds.Top;
            float fontHeight = printFont.GetHeight(PE.Graphics);
            float linesPerPage = (PE.MarginBounds.Height / fontHeight) - 1;
            PE.Graphics.DrawString("********* Methods in file : " + FName,
                    printFont, Brushes.Black, leftMargin, topMargin, new StringFormat());
            while (count < linesPerPage)
            {
                yPos = topMargin + count * fontHeight;
                if (count >= listBox1.Items.Count) break;
                PE.Graphics.DrawString( listBox1.Items[count].ToString(), 
                    printFont, Brushes.Black, leftMargin, yPos, new StringFormat());
                count++;
            }
            if (count < listBox1.Items.Count) PE.HasMorePages = true;
        }

        private void PrintPreviewBtn_Click(object sender, EventArgs e)
        {
            PrintPreviewDialog printPreviewDlg = new PrintPreviewDialog();
            ((Form)printPreviewDlg).WindowState = FormWindowState.Maximized;
            printPreviewDlg.Document = PrintDoc; //give the PrintDoc to the preview dialog
            printPreviewDlg.Show(); 
        }

        private void PrintBtn_Click(object sender, EventArgs e)
        {
            //Print the document, fires the PrintPage eventhandler
            // prints a page.
            PrintDoc.Print();
        }
    }
}
ddanbe 2,724 Professional Procrastinator Featured Poster

Unfortunately a slight mistake happened on line 100.
Line 100 should read int count = 0;
Excuse me for the eventual inconveniance.

lxXTaCoXxl 26 Posting Whiz in Training

Why not use Type.GetMethods to get just the methods instead of searching for keywords in the file. I took a second to write an example (though not as detailed as yours) it can be modified to implement with opening a specific file.

        private void button1_Click(object sender, EventArgs e) {
            ListMethods(typeof(int));
        }

        private void ListMethods(Type t) {
            foreach (var m in t.GetMethods()) {
                var p = string.Join
                    (", ", m.GetParameters()
                                 .Select(x => x.ParameterType + " " + x.Name)
                                 .ToArray());

                richTextBox1.Text += (string.Format("{0} {1} ({2})\n",
                                  m.ReturnType,
                                  m.Name,
                                  p));
            }
        }

Untitled-3.jpg

Obviously with mine you could add a drop down menu or use radio buttons to select which type of method you wish to look for (and a little more work has to be done to reveal private and protected methods) and if you use a drop down menu just add an all option. Just a thought, but yours is a good approach as well. Nice work!

ddanbe commented: Thanks for your tip! +15
JOSheaIV 119 C# Addict

You know ddanbe, I think I still have it, but I wrote a Regular Expression pattern that could pick up functions (like what you listed there). YOu wouldn't be interest in that would you?

It's been awhile since I used it, I wrote it for a program at work, where I could read in our code, and then generate a flow chart based on the function calls (as well as some other pieces of code that would progress the code)

ddanbe 2,724 Professional Procrastinator Featured Poster

Hi, Ange1ofD4rkness. Yes, I (and perhaps other members here) would of course be interested. I always had an interest in regex, the only problem I have with it is trying to remember all those rules... :)

JOSheaIV 119 C# Addict

Okay I'll try and dig it up, it might be a little messy (my developing has changed in the last year for the better .. including my Regex).

As for regular expressions, the best way is practice. I love using it so I find every excuse I can to write it (I do admit I also have a nack for it)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.