Thursday, 4 July 2019

How to check windows service is running or not in c#.

Hi All,

I have created console application to verify the installed service status running or stopped.

Below are code.
1) Add below the keys in your application.

 <add key ="ServicesName" value="SCardSvr,SNMPTRAP,Appinfo"></add>
  <add key ="ToEmail" value="abc@gmail.com"></add>
  <add key ="ProjectName" value="HIP Teva"/>
  <add key ="EnvironmentName" value="Test"/>
  <add key ="FromEmail" value="abc@gmail.com"/>
   <!--Email body in in key-->
   <add key="EmailTemplate" value="Hi %ToEmail% , &lt;br&gt;&lt;br&gt;Please verify below service on  %environmentName% environment. &lt;br&gt; &lt;br&gt; %stoppedServices% Sever IP address : %serverIP% &lt;br&gt;&lt;br&gt;&lt;br&gt; Thanks"></add>

2) Add System.ServiceProcess on your project references from NuGet


3) Add below code.

 static void Main(string[] args)
        {
            var serviceNamesCommaseparated = ConfigurationManager.AppSettings.Get("ServicesName");

            string stoppedService = string.Empty;

            if (!string.IsNullOrEmpty(serviceNamesCommaseparated))
            {
                var serviceNamelist = serviceNamesCommaseparated.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                // To Loop through
                foreach (string servicename in serviceNamelist)
                {
                    if (!string.IsNullOrEmpty(servicename))
                    {
                        var status = GetServiceStatus(servicename);

                        if (status == "Stopped" || status == "Stopping" || status == "Paused")
                        {
                            stoppedService = stoppedService + "Service Name: " + servicename + " || Status: " + status + "</br></br>";
                        }
                    }
                }

                if (!string.IsNullOrEmpty(stoppedService))
                {
                    //Send Emial to the admin and also log in log file 
                    WriteLog("Services status : " + stoppedService + "");
                    sendemail(stoppedService);
                }
            }
        }

        private static string GetServiceStatus(string serviceName)
        {

            // Verify server name is installed or not in server
            var getallservices = ServiceController.GetServices();
            string serviceStatus = string.Empty;
            if (getallservices.Where(q => q.ServiceName == serviceName) != null)
            {
                ServiceController sc = new ServiceController(serviceName);
                switch (sc.Status)
                {
                    case ServiceControllerStatus.Running:
                        return "Running";
                    case ServiceControllerStatus.Stopped:
                        return "Stopped";
                    case ServiceControllerStatus.Paused:
                        return "Paused";
                    case ServiceControllerStatus.StopPending:
                        return "Stopping";
                    case ServiceControllerStatus.StartPending:
                        return "Starting";
                    default:
                        return "Status Changing";
                }
            }
            else
            {
                WriteLog("Provided service is not installed in server " + serviceName + "");
            }
            return serviceStatus;
        }

        public static bool WriteLog(string strMessage)
        {
            try
            {
                StreamWriter log;
                if (!File.Exists("logfile.txt"))
                {
                    log = new StreamWriter("logfile.txt");
                }
                else
                {
                    log = File.AppendText("logfile.txt");
                }
                // Write to the file:
                log.WriteLine(DateTime.Now);
                log.WriteLine(strMessage);
                log.WriteLine();
                // Close the stream:
                log.Close();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        public static void sendemail(string stoppedServices)
        {
            try
            {
                MailMessage mm = new MailMessage();
                mm.From = new MailAddress(ConfigurationManager.AppSettings.Get("FromEmail"));
                mm.Subject = ConfigurationManager.AppSettings.Get("ProjectName");
                var ToEmail = ConfigurationManager.AppSettings.Get("ToEmail");
                var environmentName = ConfigurationManager.AppSettings.Get("EnvironmentName");
                mm.Subject = ConfigurationManager.AppSettings.Get("ProjectName");
                string fRecepientEmail = ConfigurationManager.AppSettings.Get("FromEmail");
                string EmailTemplate = ConfigurationManager.AppSettings.Get("EmailTemplate");
                string hostName = Dns.GetHostName(); // Retrive the Name 
                string serverIP = Dns.GetHostByName(hostName).AddressList[0].ToString();
                mm.Body = EmailTemplate.Replace("%ToEmail%", ToEmail).Replace("%environmentName%", environmentName).Replace("%stoppedServices%", stoppedServices).Replace("%serverIP%", serverIP);
                foreach (var RecepientEmail in fRecepientEmail.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries)) { mm.To.Add(RecepientEmail); }
                mm.IsBodyHtml = true;
                SmtpClient smtpMail = new SmtpClient();
                smtpMail.Send(mm);
            }
            catch (SmtpException smEx)
            {
                WriteLog(smEx.InnerException.ToString());
            }
        }

I have added to all services that need to be verify in web.config file. If services are stopped or postponed then application send the email in provided email. 

Thanks for reading.