Friday, August 31, 2012

c# - Check SQL Server is running else send notification

I have posted code to list all the windows services on a server in my previous post.Recently I had to upgrade one of our production database server and over the weekend the server crashed.I did not catch it till the next monday when I tried to write a query against one of the databases on the production server.

So I decided to write a program that would run every 15 mins to check whether the production database server is down and if it is down send an email to me so that I can take necessary action.Below is the code.


 static void Main(string[] args)
        {
            try
            {
                string [] sServerList = ConfigurationSettings.AppSettings["SERVER_LIST"].Split(',');

                foreach(string sServer in sServerList)

                {
                    if(CheckServiceRunning(sServer,"SQL Server (MSSQLSERVER)") != "Running")
                        SendMail("WARNING:Production Database Server:"+  sServer + " is not running !","DATABASE SERVER DOWN",new string[] {"me@mycompany.com,mymanager@mycompany.com" });
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        private static string CheckServiceRunning(string sServerName, string sServiceName)
        {
            ServiceController[] oaServiceController = ServiceController.GetServices(sServerName);
            foreach (ServiceController sc in oaServiceController)
            {
                if (sc.DisplayName == sServiceName)
                    return sc.Status.ToString();
            }
            return string.Empty;
        }
        public static void SendMail(String message, String subject, String[] notificationList)
        {
            try
            {
                MailMessage MyMessage = new MailMessage();
                MyMessage.From = new MailAddress("me@mycompany.com");
                foreach (String email in notificationList)
                    MyMessage.To.Add(new MailAddress(email));

                MyMessage.Subject = subject;

                MyMessage.Body = message;

                SmtpClient emailClient = new SmtpClient("smtp.myoffice.mycompany.com");

                emailClient.Send(MyMessage);
            }
            catch
            {
            }
        }

No comments: