Privacy Info

Saturday, May 7, 2022

PowerShell Service Monitor



We have previously faced issue monitoring our windows service and websites. Whenever the service is down, functionality which is dependent on the service stops working. Continuously monitoring the services is difficult and not feasible. To solve this problem we came up with PowerShell script which will monitor the service, alerts when service is down and automatically restart the service. This blog post will explain you how you can create similar Service Monitor application which will make your work easier.

Create folder with below folder structure:

Logs Folder

It will have logs files after execution of PowerShell script

Settings.xml File

It will contain the configuration details of the PowerShell script 

ServiceMonitor.ps1 File

It will contain actual code for monitoring service


Code Snippets

Settings.xml

<?xml version="1.0"?>
<Settings>
	<SolrSettings>
		<SolrURL>https://localhost:8984/solr/#/</SolrURL>
		<SolrServiceName>Solr-Service</SolrServiceName>		
	</SolrSettings>				
	<EmailSettings>
		<ToEmail>"noreply@gmail.com"</ToEmail>
		<FromEmail>ServiceMonitor@gmail.com</FromEmail>
		<EmailSubject>Service is not working</EmailSubject>
		<SMTPServer>smpt.gmail.com</SMTPServer>
		<EmailPort>25</EmailPort>
	</EmailSettings>
	<LogSettings>
		<LogFileFolder>C:\User\Projects\Restart Service\Logs\</LogFileFolder>
	</LogSettings>	
</Settings>


ServiceMonitor.ps1

#Import settings from config file
$MyDir = Split-Path -Parent $MyInvocation.MyCommand.Path
[xml]$ConfigFile = Get-Content "$MyDir\Settings.xml"

#Email Configuration 
[string[]]$ToEmail = $ConfigFile.Settings.EmailSettings.ToEmail
$FromEmail = $ConfigFile.Settings.EmailSettings.FromEmail
$EmailSubject = $ConfigFile.Settings.EmailSettings.EmailSubject
$EmailSmtpServer = $ConfigFile.Settings.EmailSettings.SMTPServer
$EmailPort = $ConfigFile.Settings.EmailSettings.EmailPort
$ErrorEmailMessage = ""
$ExceptionErrorEmailMessage=""

#LogFile Details
$TodayDate = Get-Date -format "dd-MM-yyyy"
$LogFileFolder = $ConfigFile.Settings.LogSettings.LogFileFolder
$LogFileName = $LogFileFolder+"ServiceMonitor-"+$TodayDate+".txt"
$LogMessage = ""  

#Solr Details
$SolrURL = $ConfigFile.Settings.SolrSettings.SolrURL
$SolrServiceName = $ConfigFile.Settings.SolrSettings.SolrServiceName

try{    
    $LogMessage +="`nStart - $((Get-Date).ToString())"

    $HTTP_Request = [System.Net.WebRequest]::Create($SolrURL)

    $HTTP_Response = $HTTP_Request.GetResponse()

    $HTTP_Status = [int]$HTTP_Response.StatusCode
    
    if($HTTP_Status -eq 200) {
        Write-Host "Solr Site is working"
        $LogMessage +="Solr Site is working`n"
    }
    else
    {
	throw "Solr website Error Occured" 								 			
    }  

}
catch{
	Write-host "Solr Site is down Error Occured:  $_"
	$LogMessage +="Solr Site is down Error Occured: $_`n"    	       
                
        #Restart Service       
        Invoke-Command -ScriptBlock { Restart-Service -Name  $args }  -ArgumentList $SolrServiceName
        Write-Host "Service Restarted"
        $LogMessage +="Service Restarted`n"
               
        
        #Send Email
        $ErrorEmailMessage = "URL: "+$solrURL+"`nError Details:"+$_+"`nSolr site was down`nService Restared"
        Send-MailMessage -To $ToEmail -From $FromEmail  -Subject $EmailSubject  -Body $ErrorEmailMessage  -SmtpServer $EmailSmtpServer  -Port $EmailPort			       
        Write-Host "Email Sent"
        $LogMessage +="Email Sent`n"						 		
		       	
}
finally{
    # Closing Objects
    If ($HTTP_Response -eq $null) { } 
    Else { $HTTP_Response.Close() }
}  
     
$LogMessage +="End - $((Get-Date).ToString())"
Add-Content $LogFileName $LogMessage


Sample Log File





You can also deploy code on Task Scheduler and monitor your service continuously.

I hope you will find the blog useful 😃


Website Page Capture - Console Application


Sometime we require to check website pages whether site is displaying proper content or not. Before performing deployment or any other code changes to your website how is the content current displayed on website pages. To solve this problem we have created Website Page Capturer which will take screenshot of entire website page of mentioned URL's and store images in the folder. Below blog describes how to can create this console application.

1. Create console application in Visual Studio.
2. Install below Package using Nugget Package Manager
    - Selenium.Chrome.WebDriver
    - Selenium.WebDriver
    - Noksa.WebDriver.ScreenshotsExtensions

3. Add the below code in Program.cs file 
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.Extensions;
using System;
using System.IO;
using System.Reflection;
using System.Threading;
using WDSE;
using WDSE.Decorators;
using WDSE.ScreenshotMaker;

namespace WebsiteScreenshotsCapture
{
    class Program
    {
        public static void FullWebPageScreenShotCapture()
        {
            try
            {
                string[] Urls = { "https://www.cleartrip.com/",
                                   "https://www.olx.in/",
                                   "https://www.amazon.com/",
                                   "https://www.ebay.com/"
                                };

                string ScreenShotsLocations = @"C:\User\Projects\WebsiteScreenshotsCapture\Pages\";
                string DateTimeProperFormat = String.Format("{0}-{1}-{2}-{3}-{4}-{5}", DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);


                ChromeOptions options = new ChromeOptions();
                options.AddArgument("headless");//Comment if we want to see the window. 
                options.AddArgument("--log-level=3");// Hides log errors/warnings
                ChromeDriver driver = new ChromeDriver(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), options);                
                driver.Manage().Window.Maximize();

                //Creating folder 
                string foldername = String.Format(@"{0}/{1}/", ScreenShotsLocations,DateTimeProperFormat);
                System.IO.Directory.CreateDirectory(foldername);

                Console.Clear();
                Console.WriteLine("Application Started");
                Console.WriteLine("Starting to Take Screenshots..........");
                for (int i = 0; i < Urls.Length; i++)
                {
                    driver.Url = Urls[i];   
                    
                    VerticalCombineDecorator vcd = new VerticalCombineDecorator(new ScreenshotMaker().RemoveScrollBarsWhileShooting());
                    driver.TakeScreenshot(vcd).ToMagickImage().ToBitmap().Save(String.Format("{0}Image{1}.png", foldername, i + 1));
                    Console.WriteLine("{0}- Captured",Urls[i]);
                }
                Console.WriteLine("Task Completed..........");
                
                driver.Quit();

            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception {0}",ex);
            }
            finally
            {
                Console.WriteLine("Press any key to exit......");
                Console.ReadKey();
            }
           
        }
              
        static void Main(string[] args)
        {
            FullWebPageScreenShotCapture();
        }
    }
}

Note: You can move configuration file in App.config for demonstration purpose I have added that in same file


After executing the application you will see folder is created on mentioned location in code and created folder will have screenshots of the website pages.

Console Output













Folder Created









Website Screenshots












Hope you find this blog useful 😀



Sitecore PowerShell Script - Remove item from Workflow

We came across scenario where we need to remove multiple items from workflow. If items would be less then there would not be any issue but i...