Click here to Skip to main content
15,896,359 members
Articles / Desktop Programming / Windows Forms

Finding Undisposed Objects

Rate me:
Please Sign up or sign in to vote.
4.93/5 (105 votes)
13 Aug 2009Ms-PL5 min read 199.6K   2.9K   235  
An application to find undisposed objects in your .NET application.
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.Diagnostics;

namespace UndisposedViewer
{
    public partial class MainForm : Form
    {
        string configFilePath;
        FinalizerTypeFinder typeFinder = new FinalizerTypeFinder();

        public MainForm()
        {
            InitializeComponent();
        }

        private void browseButton_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog ofd = new OpenFileDialog())
            {
                if (ofd.ShowDialog(this) == DialogResult.OK)
                {
                    executablePathTextBox.Text = ofd.FileName;
                }
            }
        }

        private void goButton_Click(object sender, EventArgs e)
        {
            WriteConfigFile();

            var processStartInfo = new ProcessStartInfo(executablePathTextBox.Text, commandlineArgumentsTextBox.Text);

            processStartInfo.EnvironmentVariables["COR_ENABLE_PROFILING"] = "1";
            processStartInfo.EnvironmentVariables["COR_PROFILER"] = "{91EFB870-F9E2-4788-A47C-8F630302A10E}";
            processStartInfo.UseShellExecute = false;

            Process process = Process.Start(processStartInfo);
            process.EnableRaisingEvents = true;
            process.Exited += new EventHandler(process_Exited);

            goButton.Enabled = false;
            logfilePathTextBox.Enabled = false;
        }

        private void WriteConfigFile()
        {
            using (StreamWriter writer = new StreamWriter(configFilePath))
            {
                writer.WriteLine(executablePathTextBox.Text);
                writer.WriteLine(commandlineArgumentsTextBox.Text);
                writer.WriteLine(logfilePathTextBox.Text);
                writer.WriteLine(false);
                writer.WriteLine(typeFilterTextBox.Text);
            }
        }

        void process_Exited(object sender, EventArgs e)
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new MethodInvoker(() => process_Exited(sender, e)));
                return;
            }

            goButton.Enabled = true;
            logfilePathTextBox.Enabled = true;

            var currentApplicationPath = Path.GetDirectoryName(Application.ExecutablePath);
            var processStartInfo = new ProcessStartInfo(
                Path.Combine(currentApplicationPath, "UndisposedLogViewer.exe"),
                "\"" + logfilePathTextBox.Text + "\"");
            Process process = Process.Start(processStartInfo);
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            InitializeConfiguration();
            TryLoadConfiguration();
        }

        private void TryLoadConfiguration()
        {
            if (File.Exists(configFilePath))
            {
                using (StreamReader reader = new StreamReader(configFilePath))
                {
                    executablePathTextBox.Text = reader.ReadLine();
                    commandlineArgumentsTextBox.Text = reader.ReadLine();
                    logfilePathTextBox.Text = reader.ReadLine();
                    bool forceGCDuringShutdown = bool.Parse(reader.ReadLine());

                    string line = null;
                    while ((line = reader.ReadLine()) != null)
                    {
                        typeFilterTextBox.AppendText(line + Environment.NewLine);
                    }
                }
            }
        }

        private void InitializeConfiguration()
        {
            var appDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            var configFileDir = System.IO.Path.Combine(appDir, "Undisposed");

            if (!Directory.Exists(configFileDir))
                Directory.CreateDirectory(configFileDir);

            configFilePath = System.IO.Path.Combine(configFileDir, "config.txt");
        }

        string originalLabel = "";
        private void findFinalizableTypesLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (string.IsNullOrEmpty(executablePathTextBox.Text))
            {
                MessageBox.Show("The executable assembly's path is required to find all finalizable types. Please enter the executable's path.");
                return;
            }

            if (finalizableTypeFinderWorker.IsBusy && !finalizableTypeFinderWorker.CancellationPending)
            {
                finalizableTypeFinderWorker.CancelAsync();
                findFinalizableTypesLabel.Text = "Cancelling...";

                return;
            }

            originalLabel = findFinalizableTypesLabel.Text;
            findFinalizableTypesLabel.Text = "Cancel";
            finalizableTypeFinderWorker.RunWorkerAsync(executablePathTextBox.Text);
        }

        private void finalizableTypeFinderWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            string assemblyPath = (string)e.Argument;
            
            foreach (Type t in typeFinder.Find(assemblyPath, true))
                finalizableTypeFinderWorker.ReportProgress(0, t.FullName);
        }

        private void finalizableTypeFinderWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            typeFilterTextBox.AppendText((string)e.UserState + Environment.NewLine);
        }

        private void finalizableTypeFinderWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            findFinalizableTypesLabel.Text = originalLabel;

            if (e.Error != null)
            {
                MessageBox.Show(e.Error.ToString(), "Undisposed - Error finding finalizable types", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL)


Written By
Software Developer Atmel R&D India Pvt. Ltd.
India India
I'm a 27 yrs old developer working with Atmel R&D India Pvt. Ltd., Chennai. I'm currently working in C# and C++, but I've done some Java programming as well. I was a Microsoft MVP in Visual C# from 2007 to 2009.

You can read My Blog here. I've also done some open source software - please visit my website to know more.

Comments and Discussions