Tuesday, March 28, 2023

How to perform Actions on App Pool across all servers for specific environment

 

We can run set of command on specific host machine remotly using  Invoke-Command

```
 Invoke-Command  -ComputerName $hostname -ScriptBlock {
 param($apn)
 Import-Module WebAdministration ;
 Get-WebAppPoolState $apn} -Args $appPoolName
```

 >  **pre-requisites** for Invoke-Command are 
 - **WinRM service** should be running state in both host machine (where triggering commands ) and remote host machine (where executing commands)
 - **5985(for http)\5986 (https)** port should be opened between host machine and remote machine.

 > We can check WinRm Service is running or not usign below command

```
	Get-Service |Where-Object{$_.Name -eq "WinRm" -and $_.Status -eq "Running"}
```

> We can check WinRm port is opened between two servers 

```
 	TNC  -CommonTCPPort WINRM
```

-  IISAdministration module is newer version of Administration module. This module cmdlets will provide better support for the pipeline and scale better.

- WebAdministration is legacy version of IIS Administration module , this module cmdlets contains more efficient code.

- If it is web server , `IIS Management services`,`IIS Management scripts and Tools` features are enabled under `Web mangement Tools`section in 'Windows Features` (Appwiz.cpl)
   > we can install IISAdministration IISAdministration PowerShell Module from the PowerShell Gallery

```
   Install-Module IISAdministration
   Install-Module WebAdministration ##Legacy version
```

#### App pool commands 
1. `Get-WebAppPoolState` cmdlet used to get state of the app pool whether App pool is Started or stopped or Starting or Stopping

```
function  Get-AppPoolStatus(){
    [CmdletBinding()]
            Param(
            [Parameter(Mandatory=$true)]
            $appPoolName)

    Import-Module WebAdministration ;
    $appPoolStatus=Get-WebAppPoolState -Name $appPoolName
    
    $status =$appPoolStatus.Value
    Write-Host "Status of the $appPoolName app pool is $status in $hostname"
    return $status
}

$appPoolName="UserAppPool"

$status =Get-AppPoolStatus -HostName "WebServer-01"  -appPoolName $appPoolName
```

2. `Start-WebAppPool` cmdlet is used to start particular app pool
  > Note: It will throw execption if App pool doesn't exist or App pool is already started.

```
function  Start-AppPool(){
    [CmdletBinding()]
            Param(
            [Parameter(Mandatory=$true)]
            $appPoolName)

    Import-Module WebAdministration ;
    Start-WebAppPool -Name $appPoolName
    return $status
}

$appPoolName="UserAppPool"
$status =Start-AppPool -HostName "WebServer-01"  -appPoolName $appPoolName
```


3. `Stop-WebAppPool` cmdlet is used to stop particular app pool
  > Note: It will throw execption if App pool doesn't exist or App pool is already stopped.

```
function  Stop-AppPool(){
    [CmdletBinding()]
            Param(
            [Parameter(Mandatory=$true)]
            $appPoolName)

    Import-Module WebAdministration ;
    Stop-WebAppPool -Name $appPoolName
 }

$appPoolName="UserAppPool"
$status =Start-AppPool -HostName "WebServer-01"  -appPoolName $appPoolName
```

4. `Restart-WebAppPool` cmdlet is used to stop particular app pool
  > Note: It will throw execption if App pool doesn't exist or App pool is already stopped.

```
function  Restart-AppPool(){
    [CmdletBinding()]
            Param(
            [Parameter(Mandatory=$true)]
            $appPoolName)

    Import-Module WebAdministration ;
    Restart-WebAppPool -Name $appPoolName
 }

$appPoolName="UserAppPool"
$status =Start-AppPool -HostName "WebServer-01"  -appPoolName $appPoolName
```

   > Note: How to convert string to script block

```
        $cmd="Import-Module WebAdministration; $Operation -Name $appPoolName"
        $scriptBlock=[scriptblock]::Create($cmd)
```

Here is the [complete script ](https://raw.githubusercontent.com/KollaRajesh/aztdPowershellAutomation/main/AppPool/AppPool.ps1) to make actions on specific App pool in specific machine remotely.

Thursday, March 23, 2023

How to connect to List of servers using mstsc terminal with saved credentials using PowerShell




We can prompt window to get credentails of user with the help of `Get-Credentials commandlet 
and it will captured password as secureString  [System.Security.SecureString]
 
```sh 
	Get-Credential -UserName $env:UserName -Message 'Please enter password'
    
```
Alternative way to capature password as secureString  [System.Security.SecureString]

```sh 
	$pw =Read-Host  "Enter Password"  -AsSecureString
```

`cmdkey` utility is used to add\delete\list domain,generic,smart card & rsa credentials into windows credentials store 

 -	Syntax
    
```sh

 To list available credentials:
     cmdkey /list
     cmdkey /list:targetname

  To create domain credentials:
     cmdkey /add:targetHostOrIp /user:username /pass:password
     cmdkey /add:targetHostOrIp /user:username
     cmdkey /add:targetHostOrIp /smartcard
     
  To create generic credentials:
     The /add switch may be replaced by /generic to create generic credentials
     
     cmdkey /generic:targetHostOrIp /user:username /pass:password
     cmdkey /generic:targetHostOrIp /user:username
     cmdkey /generic:targetHostOrIp /smartcard
     
  To delete existing credentials:
     cmdkey /delete:targetHostOrIp

  To delete RAS credentials:
     cmdkey /delete /ras
```
 - Example
 
```sh
	
    ## Adding generic credentials into windows credential store  for Server1 
    cmdkey /generic:Server1 /user:$userName /pass :$pwd

    ## Adding generic credentials with TERMSRV into windows credential store  for Server2
    cmdkey /generic:TERMSRV/Server1 /user:$userName /pass :$pwd
    
    ##Adding domain credentials into windows credential store  for Server3
    cmdkey /add:Server3 /user:$userName  /pass:$pwd

	##delete saved credentials from windows credential store for Server1
    cmdkey /generic:Server1 
  	
    ##delete saved credentials from windows credential store for Server2
    cmdkey /generic:Server2
    
    ##delete saved credentials from windows credential store for Server3
    cmdkey /generic:Server3 

```


### Here is complete script to connect to list of servers using mstsc terminal with saved credentials using PowerShell.

> Note: 

 1. Server host names should be replaced with actual servers in adding into webBackendActiveServers
 2. DR Server host Names should be replaced with actual servers in adding into webBackendDRServers

```sh
$webBackendServers=New-Object Collections.Generic.List[String]
$webBackendActiveServers=New-Object Collections.Generic.List[String]
$webBackendDRServers=New-Object Collections.Generic.List[String]

$webBackendActiveServers.AddRange([string[]]@("BE-Server1","BE-Server2","BE-Server3","BE-Server4","BE-Server5","BE-Server6"))
$webBackendDRServers.AddRange([string[]]@("BE-DR-Server1","BE-DR-Server2","BE-DR-Server3","BE-DR-Server4","BE-DR-Server5","BE-DR-Server6"))

$credentials = Get-Credential -UserName $env:UserName -Message 'Please enter password'

$userName =$credentials.UserName
$credentials.Password
$pwd=$credentials.GetNetworkCredential().Password

$webBackendServers.AddRange($webBackendActiveServers)
$webBackendServers.AddRange($webBackendDRServers)

$webBackendServers | Foreach-Object {
    ## Adding credentials into windows credential store  for hostname 
    cmdkey /generic:$_ /user:$userName /pass :$pwd

    ##If above command doesn't work then try with below command to add credentials into windows credential store  for hostname 
    ##cmdkey /generic:TERMSRV/$_ /user:$userName /pass :$pwd
    
    ##If above two command don't work then try with below command to add credentials into windows credential store  for hostname 
    ##cmdkey /add:$_ /user:$userName  /pass:$pwd
    mstsc /v:$_ /f

    }

$remove =cmdkey  /list | &{Process {if ($_ -like "*Target=*" -and $webBackendServers.Contains($_.Split("=")[1].Trim())){
$_.Split("=")[1].Trim()}}};

$remove| &{Process {
        
    ## clearing credentials from  windows credential store for hostname 
        cmdkey /delete:$_
        
        ##if use TERMSRV while adding credentials into windows credentials store then uncomment below line of code
        ##cmdkey /delete:TERMSRV/$_}
        };

```





Saturday, March 18, 2023

.NET command-line interface (CLI)


# [Overview of .NET CLI](https://learn.microsoft.com/en-us/dotnet/core/tools/)

The .NET command-line interface (CLI) is a cross-platform tool chain for developing,
 building, running, and publishing .NET applications. 

#### Here is list of command to create list of projects with console app template using dotnet cli

```cs
	$solutionName="ConsoleApp"
	$solutionPath="c:\temp\dotnet\ConsoleApp"
	dotnet new sln -n $solutionName -o $solutionPath

	cd $solutionPath

 	dotnet new console  -o  "$solutionName.UI"  -lang "c#"  -f net7.0
 	dotnet new console  -o  "$solutionName.UI.Tests"
 	dotnet new console  -o  "$solutionName.ApiService"
 	dotnet new console  -o  "$solutionName.ApiService.Tests"
 	dotnet new console  -o  "$solutionName.Business"
 	dotnet new console  -o  "$solutionName.Business.Tests"
 	dotnet new console  -o  "$solutionName.Data"
 	dotnet new console  -o  "$solutionName.Data.Tests"
```
#### Adding projects to solution using dotnet cli

> Note: Below ls command will work for `Powershell`

```sh
 	dotnet sln "$solutionName.sln" add (ls -r **/*.csproj) 
```

#### Adding project references using dotnet cli

```sh
  	dotnet add "$solutionName.UI/$solutionName.UI.csproj" reference 
   		"$solutionName.ApiService/$solutionName.ApiService.csproj"

	dotnet add "$solutionName.ApiService/$solutionName.ApiService.csproj" 
 	 reference "$solutionName.Business/$solutionName.Business.csproj"

    dotnet add "$solutionName.Business/$solutionName.Business.csproj" 
  		reference "$solutionName.Data/$solutionName.Data.csproj"

  	dotnet add "$solutionName.UI.Tests/$solutionName.UI.Tests.csproj" 
   		reference "$solutionName.UI/$solutionName.UI.csproj"

  	dotnet add "$solutionName.ApiService.Tests/$solutionName.ApiService.Tests.csproj"
   		reference "$solutionName.ApiService/$solutionName.ApiService.csproj"

  	dotnet add "$solutionName.Business.Tests/$solutionName.Business.Tests.csproj"
 		reference "$solutionName.Business/$solutionName.Business.csproj"

  	dotnet add "$solutionName.Data.Tests/$solutionName.Data.Tests.csproj"
 		reference "$solutionName.Data/$solutionName.Data.csproj"
```

#### Build solution using dotnet cli

```sh
	dotnet build "$solutionName.sln"
```  


#### Here is list of commands to create list of projects using specific project type templates  using dotnet cli

####  Following list of commands to create solution file for adding specific project later

```sh
/*Input to specify project type 
  List of avaiable project types :webApp |mvc|angular|react|blazorserver|blazorwasm|wpf|winforms|      */ 

 $projectType= "WebApp"  
    
 $solutionPath="c:\temp\dotnet"

 if ($projectType -eq "WebApp"){ $solutionName=$projectType }
 	else{ $solutionName="$projectType-App"}

 if ($projectType -eq "blazorwasm"){ $framework="net6.0"} else{$framework="net7.0" }
	$solutionPath="$solutionPath\$solutionName"

	dotnet new sln -n $solutionName -o $solutionPath
```
####  Following list of commands to create projects with specific project types for each layer.

```sh
	cd $solutionPath

/*Create C# project with specific ui project template and specific framework.*/
 	dotnet new $projectType.ToLower() -o  "$solutionName.UI"  -lang "c#"  -f $framework
 	
/*Create test project for ui project with nunit project template*/
    dotnet new nunit -o  "$solutionName.UI.Tests"
	
/*Create C# project with webapi project template for api service layer*/
	dotnet new webapi  -o  "$solutionName.ApiService"
 	
/*Create test project with xunit project template for Api project.*/
	dotnet new xunit   -o  "$solutionName.ApiService.Tests"
 	
/*Create C# project with classlib project template for business layer.*/
	dotnet new classlib  -o  "$solutionName.Business"
    
/*Create C# project with mstest project template for Business project.*/
 	dotnet new mstest  -o  "$solutionName.Business.Tests"
 	
/*Create C# project with classlib project template for data layer.*/
    dotnet new classlib -o  "$solutionName.Data"

/*Create C# project with nunit project template for Data layer*/
	dotnet new nunit -o  "$solutionName.Data.Tests"

```
#### Adding projects to solution file.

```sh
/*Adding all projects to solution.*/
    dotnet sln "$solutionName.sln" add (ls -r **/*.csproj) 
```

```sh
 dotnet add "$solutionName.UI/$solutionName.UI.csproj"
   	reference "$solutionName.ApiService/$solutionName.ApiService.csproj"

 dotnet add "$solutionName.ApiService/$solutionName.ApiService.csproj" 
   	reference "$solutionName.Business/$solutionName.Business.csproj"

 dotnet add "$solutionName.Business/$solutionName.Business.csproj"
   	reference "$solutionName.Data/$solutionName.Data.csproj"

 dotnet add "$solutionName.UI.Tests/$solutionName.UI.Tests.csproj"
   	reference "$solutionName.UI/$solutionName.UI.csproj"

 dotnet add "$solutionName.ApiService.Tests/$solutionName.ApiService.Tests.csproj"
 	reference "$solutionName.ApiService/$solutionName.ApiService.csproj"

 dotnet add "$solutionName.Business.Tests/$solutionName.Business.Tests.csproj"
 	reference "$solutionName.Business/$solutionName.Business.csproj"
  
 dotnet add "$solutionName.Data.Tests/$solutionName.Data.Tests.csproj" 
 	reference "$solutionName.Data/$solutionName.Data.csproj"
```
#### Build solution

```sh
 	dotnet build "$solutionName.sln"
```
 
- References
    [dotnet tools](https://learn.microsoft.com/en-us/dotnet/core/tools/)

	- List dotnet runtimes installed 
   	  
    	```sh
    		dotnet  --list-runtimes
    	```
	- List dotnet SDKs installed 
    
      ```sh
			dotnet  --list-sdks
	  ```
   		
	- Latest installed dotnet version  
   
   	 ```sh
 			dotnet  --version
   	 ```
 
 

- New project or Project item
   
 	Below Command show help for the C# console application template:

	```sh
      	dotnet new console -h
     ```
    
    Create a C# console application project:
  		
    ```sh
     	dotnet new console
  	```
    
  	Create an C# console application project in the current directory
  	  
      ```sh
		dotnet new console --language "C#"
  	  ```
  	  
      Create an C# Blazor server application project in the current directory with no https protocal
  		
      ```sh
  		dotnet new blazorserver -o BlazorApp --no-https
  	  ```
 
 	  Create an C# Blazor web assembly project  in the current directory with no https protocal
 	  
      ```sh
  			dotnet new blazorwasm -o BlazorWasmApp --no-https
  	  ```

 	  Create a .NET Standard 4.0 class library project in the specified directory:
  		
      ```sh
  			dotnet new classlib --framework "netstandard4.0" -o MyLibrary
  	  ```
  		
      Create a new ASP.NET Core C# MVC project in the current directory with no authentication:
  			
      ```sh
  			dotnet new mvc -au None
  	  ```
  		
      Create a new xUnit project:
        
      ```sh
          dotnet new xunit
      ```
        
      Create a global.json in the current directory setting the SDK version to 3.1.101:
         
      ```sh
          dotnet new globaljson --sdk-version 3.1.101
      ```
      
      Show help for the VB console application template:
         
      ```sh
         dotnet new console --language "VB" -h
      ```
 
 	- Create Solution file 
   
 	   Below Command show help for solution
  		 ```sh
    		dotnet sln [command] -h|--help
   		 ```
    
     Syntax
  	  ```sh
    	dotnet sln [] [command]
   	  ```
     
     Creates a .sln file in the current folder, with the same name as the folder:
     ```sh
     	dotnet new sln
	 ```
     Creates a .sln file in the current folder, with the specified file name:
     ```sh
        dotnet new sln --name MyApp
     ```
    
    Creates a .sln file in the specified folder, with the same name as the folder:
    ```sh
    	dotnet new sln --output C:\temp\App
     ```
 

Tuesday, March 14, 2023

Rewriting your git history by removing secret\confidential values permanently


## Rewriting your git history, removing files permanently 

#### Problem:
 - Committing secret , Keys , token values in git is potentially security risk. 
 - If we deleted \ remove Keys , secret , token or any security information  later in the next commit .
 - Still security information in git history so it is very potential security risk.

#### Solution:
 - Rewriting your git history by removing secret\confidential values permanently [cheat sheet](https://res.cloudinary.com/da8kiytlc/image/upload/v1611932656/Cheatsheets/RewritingYourGitHistory-Cheatsheet-Final_weq1l2.pdf?ref=gitguardian-blog-automated-secrets-detection)

` Installation of git-filter-repo `

1. Install Python.
2. Check "Add Python to environment variables" in Advance options while installing Python.
3. [Clone repository](https://github.com/newren/git-filter-repo.git).
4. Run the command git --exec-path to see your Git exe directory.
5. From the git-filter-repo repo's root directory, copy the file git-filter-repo (about 160KB) into your Git exe directory.
6. Run the command "Which python" .
7. Open git-filter-repo file ,replace first line "/usr/bin/python" with path of python (from above point).
8. Type the command git filter-repo.If it works, you should get the message "No arguments specified." 	
 
Now We can tell git-filter-repo to search for the hard-coded token\secret value , and replace with the environment variable by adding this line to replacements.txt:
 
Example

```sh
    ‘123abc’==>ENV[‘AUTH_TOKEN’]
```

If you have multiple secrets you need to excise, you can have more than one rule like this in replacements.txt.( place in the parent directory)

- Run git filter repo command with replace text switch for replacement.txt

```sh
 git filter-repo --replace-text replacements.txt
```

- Add remote Url to your local repository .Note:remote url mapping would removed after running git filter repo command

 Syntax

	```sh
		git remote add name [remoteUrl]
	```
 Example

  ```sh
    	git remote add aztd-SFTPAssistantBot https://github.com/UserName/aztd-SFTPAssistantBot.git
  ```
 Syntax
	```sh
		git push --set-upstream  main  --force
	```
 Example

 ```sh
     git push --set-upstream aztd-SFTPAssistantBot main  --force
 ```

- References

  [the-secret-is-beyond-the-last-commit](https://blog.gitguardian.com/rewriting-git-history-cheatsheet/#the-secret-is-beyond-the-last-commit?utm_source=product&utm_medium=product&utm_campaign=onboarding)
  [git-filter-repo-commands-output-nothing-on-windows](https://stackoverflow.com/questions/69355161/git-filter-repo-commands-output-nothing-on-windows)