Tuesday, 26 February 2019

Powershell - starting and stopping multiple app pools

The following powershell script defines some functions in Powershell that can start up or stop all iis app pools on a server. It can be handy when you want to test out concurrency issues and switch off all IIS app pools and start up again.

Function fnStartApplicationPool([string]$appPoolName){
Import-Module WebAdministration 
 if ((Get-WebAppPoolState $appPoolName).Value -ne 'Started') {
  Write-Host 'IIS app pool ' $appPoolName ' is not started. Starting.' 
  Start-WebAppPool -Name $appPoolName 
  Write-Host 'IIS app pool ' $appPoolName 'started' 
 }
}

Function fnStartAllApplicationPools() {
Import-Module WebAdministration  
 Write-Host "Starting all app pools" 
 $appPools = (Get-ChildItem IIS:\AppPools)

foreach ($appPool in $appPools) { 
  & fnStartApplicationPool -appPoolName $appPool.Name
}
}

#fnStartAllApplicationPools #start all applications pools


Function fnStopApplicationPool([string]$poolname) {
Import-Module WebAdministration 
 if ((Get-WebAppPoolState $appPoolName).Value -ne 'Stopped') {
  Stop-WebAppPool -Name $appPoolName 
 }
}

Function fnStopAllApplicationPools(){
Import-Module WebAdministration  
 Write-Host "Starting all app pools" 
 $appPools = (Get-ChildItem IIS:\AppPools)

foreach ($appPool in $appPools) { 
  & fnStopApplicationPool-appPoolName $appPool.Name
}  

}

#fnStopAllApplicationPools #start all applications pools


Saturday, 23 February 2019

Serializing a data contract with xml declaration and indented formatting

This code will serialize your object graph and also do xml indentation and adding an xml declaration at the top, using DataContractSerializer.



public static string SerializeObjectIndented(T dataContract, bool omitXmlDeclaration = false) where T : class
{
 using (var output = new StringWriter())
 {
  using (var writer = new XmlTextWriter(output) { Formatting = Formatting.Indented })
  {
   if (!omitXmlDeclaration)
    writer.WriteStartDocument();
   var serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(T));
   serializer.WriteObject(writer, dataContract);
   
   return output.GetStringBuilder().ToString();
  }
 }
}

To use it, just pass in your object and get an xml back!