Click here to Skip to main content
15,884,388 members
Articles / Programming Languages / C#

Monitoring a MySQL Server Process

Rate me:
Please Sign up or sign in to vote.
4.73/5 (8 votes)
26 Oct 2010CPOL2 min read 37.1K   1.4K   21  
An example of monitoring a Windows process
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Diagnostics;
using System.Text;
using System.IO;
using System.Windows.Forms;

namespace MySQLserverMonitor
{
    public partial class Form1 : Form
    {
        string appPath = null;
        bool serverStat = false;
        
        public event EventHandler<serverEventArgs> RaiseServerEvent; //declare event
        public Form1()
        {
            InitializeComponent();
            RaiseServerEvent += new EventHandler<serverEventArgs>(Form1_RaiseServerEvent); //subscribe event
        }

        void Form1_RaiseServerEvent(object sender, Form1.serverEventArgs e)
        {
            if (e.ServerStatus)
            {
                lblServerStatus.Text = "server started";
                lblServerStatus.ForeColor = Color.Green;
                lblStatusContext.Text = "server started";
                lblStatusContext.ForeColor = Color.Green;
                btnStart.Enabled = false; //this prevent user from clicking thus create new process
                btnStop.Enabled = true;
                mnuStart.Enabled = false;
                mnuStop.Enabled = true;
                notifyIcon1.Text = "mySQL server is running";                
                notifyIcon1.Icon = MySQLserverMonitor.Properties.Resources.database_server_on;
            }
            else
            {
                lblServerStatus.Text = "server stopped";
                lblServerStatus.ForeColor = Color.Salmon;
                lblStatusContext.Text = "server stopped";
                lblStatusContext.ForeColor = Color.Salmon;
                btnStop.Enabled = false; //an error will occur when no process can stop
                btnStart.Enabled = true;
                mnuStop.Enabled = false;
                mnuStart.Enabled = true;
                notifyIcon1.Text = "mySQL server is not running";
                notifyIcon1.Icon = MySQLserverMonitor.Properties.Resources.database_server_off;
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            Process[] server =  Process.GetProcessesByName("mysqld");            
            if (server.Length != 0)
            {
                bool stat = true;
                if (serverStat != stat) //check if current status same as previous. this prevent notification always shown
                {
                    OnRaiseServerEvent(new serverEventArgs(true)); //raise server event
                    serverStat = stat;
                }
                //assume just one process running
                //lblCPUcost.Text = (server[0].UserProcessorTime.Ticks / server[0].TotalProcessorTime.Ticks * 100).ToString (); //view cpu cost 
                lblHost.Text = server[0].MachineName;
                lblMemCost.Text = server[0].WorkingSet64.ToString() + " Bytes";
                lblNPmemsize.Text = server[0].NonpagedSystemMemorySize64.ToString() + " Bytes";
                lblPID.Text = server[0].Id.ToString();
                lblStartTime.Text = server[0].StartTime.ToString();
            }
            else
            {
                bool stat = false ;
                if (serverStat != stat) //check if current status same as previous. this prevent notification always shown
                {
                    OnRaiseServerEvent(new serverEventArgs(false)); //raise server event
                    serverStat = stat; //update global status
                }          
                
            }
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            FileInfo fi = new FileInfo(appPath + "\\mysqld.exe");
            if (fi.Exists)
                Process.Start(fi.FullName);
            else
                errorProvider1.SetError(txtPath, "this isn't mysql installation directory");
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                 txtPath.Text = folderBrowserDialog1.SelectedPath;                 
            }
            folderBrowserDialog1.Dispose();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            DirectoryInfo di = new System.IO.DirectoryInfo(txtPath.Text);
            if (di.Exists)
            {
                StreamWriter confFile = new StreamWriter(System.Environment.CurrentDirectory + "\\conf.txt"); //write configuration to file
                confFile.WriteLine(di.FullName);
                confFile.Flush(); //write to stream
                confFile.Close(); //release stream and memory
                appPath = di.FullName;
                timer1.Enabled = true;
                lblServerStatus.ForeColor = Color.Black;
                btnStart.Enabled = true;
                btnStop.Enabled = true;
                errorProvider1.SetError(txtPath, "");
                timer1.Enabled = true;
                serverStat = false;
                btnStop.Enabled = false; //assume  server is stopped at application start
            }
            else
                errorProvider1.SetError(txtPath, "folder not exist");
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            FileInfo confFile = new FileInfo (System.Environment.CurrentDirectory + "\\conf.txt"); //check file
            if (confFile.Exists)
            {
                StreamReader confStream = new StreamReader(confFile.FullName); //read configuration file
                appPath = confStream.ReadLine(); //read conf data which is directory of mysql installation
                txtPath.Text = appPath;
                timer1.Enabled = true;
            }
            else
            {
                lblServerStatus.Text = "unknown mySQL installation directory";
                lblServerStatus.ForeColor = Color.Red; //show notification
                btnStart.Enabled = false; //don't let user click these button or it'll raise error
                btnStop.Enabled = false;
            }
            Process[] server = Process.GetProcessesByName("mysqld"); //check on start
            if (server.Length != 0)
            {
                OnRaiseServerEvent(new serverEventArgs(true));
                timer1.Enabled = true;
            }
            else
                OnRaiseServerEvent(new serverEventArgs(false));
        }

        private void txtPath_Validating(object sender, CancelEventArgs e)
        {
            DirectoryInfo di = new System.IO.DirectoryInfo(txtPath.Text);
            if (!(di.Exists))
                errorProvider1.SetError(txtPath, "folder not exist"); //show error message
            else
                errorProvider1.SetError(txtPath, ""); //clear error message
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            FileInfo fi = new FileInfo (appPath + "\\mysqladmin.exe");
            if (fi.Exists)
            {
                Process.Start(fi.FullName, "--user=root shutdown");
            }
            else
                errorProvider1.SetError(txtPath, "this isn't mysql installation directory");
        }

        private void restoreToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Show(); //show hidden form
        }
        /// <summary>
        /// argument on server status change
        /// </summary>
        public class serverEventArgs : EventArgs 
        {
            private bool serverStatus;
            public serverEventArgs(bool statusServer)
            {
                serverStatus = statusServer;
            }
            public bool ServerStatus
            {
                get { return serverStatus; }
                set { serverStatus = value; }
            }
        }
        
        protected virtual void OnRaiseServerEvent(serverEventArgs e)
        {
            EventHandler<serverEventArgs> handler = RaiseServerEvent; 
            //read help : how to publish Publish Events that Conform to .NET Framework Guidelines (C# Programming Guide)
            if (handler != null)
            {
                handler(this, e);
            }
        }

        private void chkOnTop_CheckedChanged(object sender, EventArgs e)
        {            
                this.TopMost = chkOnTop.Checked;
        }

        private void btnhide_Click(object sender, EventArgs e)
        {
            this.Hide(); //hide form
        }

        private void mnuExit_Click(object sender, EventArgs e)
        {
            notifyIcon1.Dispose(); 
            this.Close(); //close the form
        }
    }
}

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 Code Project Open License (CPOL)


Written By
Engineer Donatus Inc.
Indonesia Indonesia
I'm currently a student of Brawijaya University. I work on programming just for hobby. I learn programming since 2nd year of my college. That's when I first bought my PC on year 2004.

Comments and Discussions