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.

Monday, 18 March 2019

How to take all database offline at one in SQL Server

Hi All,

Today, we are going to learn how we can take all the Databases offline at one time by using SQL scripts. 

Below are the SQL scripts. 


DECLARE @dbName SYSNAME
,@query VARCHAR(MAX);
DECLARE cursor_db CURSOR
FOR
SELECT name
FROM sys.databases
WHERE owner_sid <> 0x01;
OPEN cursor_db;
WHILE 1 = 1
BEGIN
FETCH NEXT
FROM cursor_db
INTO @dbName;
IF @@FETCH_STATUS <> 0
BREAK;
SET @query = N'ALTER DATABASE [' + @dbName + N'] SET OFFLINE WITH NO_WAIT';
EXEC (@query);
END;
CLOSE cursor_db;
DEALLOCATE cursor_db;


Thanks for reading.


Wednesday, 15 November 2017

How to create query shortcut in SQL server

Hi All,  

Today I am going to explain how to create query shortcut in SQL server. 

Go to tools.




Click on Options-> Keyboard -> Query Shortcuts.

In the right site you can see query shortcuts and command. Please enter your query.



Click on save button.

Open new query window (Ctrl+N) and enter your table name.

Select your table name and press Ctrl+3 shortcut. 

Thanks for reading :) 

How to restore database by using T-SQL Scripts

Hi All,  

Today I am going to explain how to restore database by using T-SQL Scripts. We already have database in sql server and database backup file .

DECLARE @DbName nvarchar(50)
SET @DbName = N'TestDB'
DECLARE @EXECSQL varchar(max)
SET @EXECSQL = ''
SELECT @EXECSQL = @EXECSQL + 'Kill ' + Convert(varchar, SPId) + ';'
FROM MASTER..SysProcesses
WHERE DBId = DB_ID(@DbName) AND SPId  =@@SPId
EXEC(@EXECSQL)

ALTER DATABASE [TestDB] SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO

RESTORE DATABASE [TestDB] FROM DISK = 'D:\backup\TestDB.bak' WITH REPLACE 
GO

Thanks for reading. :) 

Friday, 24 March 2017

Data Type in JavaScript 

JavaScript has five primitive data type.

1  Number
2  String
3  Boolean
4  Undefined
5  Null

Any data type other than above 5 types is called object.  

In javascript there are two types to object.

  1. Build in object
  2. Custom object

Build in Object :  Examples include array, date etc. In below example we have create the object of date by using date constructor.

    var date= new Date();
    alert(date.getDate);
    alert(date.getFullYear);


Custom objects : In JavaScript we don't have classes. We use function instead of classes.
In JavaScript there are two ways to create a custom object.

1. Constructor function
2. Literal notation

Constructor Function

<script type="text/javascript">
    function Student(firstName, lastName)
    {
       this.firstName = firstName;
       this.lastName = lastName;

       this.getFullName = function ()
       {
           return this.firstName + " " + this.lastName;
       }
    }

    var student= new Student("Jitendra", "Kachhi");

    document.write("First Name :" + student.firstName + "<br/>");
    document.write("Last Name : " + student.lastName + "<br/>");
    document.write("Full Name :" + student.getFullName() + "<br/>");
</script>

literal Notation

<script type="text/javascript">
    var student=
    {
       firstName: "Jitendra",
       lastName: "Kachhi",

       FullName: function ()
       {
           return this.firstName + " " + this.lastName;
       }
    }

    document.write("FirstName = " + student.firstName + "<br/>");
    document.write("LastName = " + student.lastName + "<br/>");
    document.write("FullName = " + student.FullName() + "<br/>");
</script>

Note:- literal Notation will have only single object(singleton), if we want to create multiple object use Constructor Function.


Thanks you for reading.