Monday, July 31, 2023

Create nuget package


Nuget package is compressed file with extension *.nupkg extension and this package can be shared to other teams.

we can create nuget packages using nuget cli or dotnet cli 

#### Prerequisites

Install [Nuget.exe](https://dist.nuget.org/win-x86-commandline/latest/nuget.exe) CLI 

dotnet.exe with [DotNet SDK](https://www.microsoft.com/net/download/)


#### 1. Generate Manifest (.nuspec) 

we can generate initial .nuspec file from project 
```sh 
# we can generate .nuspec file from project file
	nuget spec Logger.csproj

#we can generate .nuspec file from project dll as well 
	nuget spec .dll

```

Note: NuGet throws  error if you try to create a package with default values in .nuspec file, so you must change the following fields before proceeding.

 - licenseUrl
 - projectUrl
 - iconUrl
 - releaseNotes
 - tags

#### 2.1 Create Package using nuget cli

```sh
# generate package by running nuget pack  where cs project located
	nuget  pack 

# generate package by specifying project location and configuration 
	nuget pack .\Logger\Logger.csproj -properties Configuration=Release

# generate package for specifying project and configuration
nuget pack Logger.csproj -properties Configuration=Release

# generate package for specifying project after building project with build configuration release and include referenced projected if project is using external project references
nuget pack Logger.csproj -Build -properties Configuration=Release  -IncludeReferencedProjects


# Create a package from Logger.csproj, using MSBuild version 12 to build the project and package properties (owner and version)
nuget pack Logger.csproj -Build -Symbols -MSBuildVersion 12 -Properties owners=scott,rob;version="1.0.0"

#create a package using nuspec file and exclude exe and bat files 

nuget pack logger.nuspec -exclude "*.exe" -exclude "*.bat"
```

#### 2.2 Create Package using dotnet cli

```sh
# generate package by running nuget pack  where cs project located
	dotnet pack

# generate package by specifying project location and configuration 
	dotnet pack .\Logger\Logger.csproj -properties Configuration=Release

# generate package for specifying project and configuration
	dotnet pack Logger.csproj -properties Configuration=Release

# generate package for specifying project after building project with build configuration release and include referenced projected if project is using external project references
dotnet pack Logger.csproj -Build -properties Configuration=Release  -IncludeReferencedProjects


# Create a package from Logger.csproj, using MSBuild version 12 to build the project and package properties (owner and version)
dotnet pack Logger.csproj -Build -Symbols -MSBuildVersion 12 -Properties owners=scott,rob;version="1.0.0"

#create a package using nuspec file and exclude exe and bat files 

dotnet pack logger.nuspec -exclude "*.exe" -exclude "*.bat"
```

#### 3. Publish Package in nuget repository 

Once .nupkg file is created , you can publish to [nuget repository](https://nuget.org)

 - Sign into [nuget.org](https://nuget.org) account or create an account if you don't have one already.
 - Click on your username which is on the upper right, and select API Keys and then on webpage click on Create.

```sh 
nuget push Logger.1.0.0.nupkg oz5fgepyspx6fzm67guqybyr8vanjboudmner4e1gsy24b -Source https://api.nuget.org/v3/index.json

#push package using dotnet cli to the default push source specified in the NuGet config file 
dotnet nuget push foo.nupkg -k 3003d786-dd37-6004-efef-d4f3e8ef9b3a

#push package using dotnet cli to nuget repository 
dotnet nuget push foo.nupkg -k 6003d786-cc36-6004-efef-d4d3e8ef9b3a -s https://api.nuget.org/v3/index.json
```
#### 3. Publish Package in Nexus repository 

Once .nupkg file is created , if want to push a NuGet package to a Nexus repository, 

we can use the nuget push command. This command requires to use the NuGet API Key and the URL of the target hosted repository 

For example, if your Nexus server is located at http://nexus_server and your repository is named nexus_nuget_repository

```sh
	nuget push [logger.nupkg] -Source http://nexus_server/repository/nexus_nuget_repository/ -ApiKey [api_key] 

#push package using dotnet cli to nuget repository 
	dotnet nuget push logger.nupkg -k 6003d786-cc36-6004-efef-d4d3e8ef9b3a -s http://nexus_server/repository/nexus_nuget_repository/

```


How to install VS code in WSL \ Linux


### Option:1 [install using apt install ]

1. If wget is not installed, please install it using the command
2. if apt-transport-https is not installed then install it using the command 
 
```sh 
 sudo apt-get install wget
 sudo apt install apt-transport-https
``` 
3. Install code package 

```sh
sudo apt update
sudo apt install code # or code-insiders
```

Note: To avoid prompting when open VS code , set DONT_PROMPT_WSL_INSTALL environment variable as 1

```sh
export DONT_PROMPT_WSL_INSTALL=1

#add below variable in   ~/.bashrc to avoid adding environment in each instance of wsl distribution

alias code='DONT_PROMPT_WSL_INSTALL=1 code'

```



### Option:2 [Install using VS code debian package]

1. downdload debian package for [VS code installer for linux](https://code.visualstudio.com/sha/download?build=stable&os=linux-deb-x64)

2. Move package to WSL home location

```sh 
mv /mnt/c/Users//<HostOS-UserId>/Downloads/code_1.80.2-1690491597_amd64.deb /home/<WSL-UserId>

```

3. Install VS code debian package [code_1.80.2-1690491597_amd64.deb]
```sh
sudo apt install ./code_1.80.2-1690491597_amd64.deb
```

Saturday, July 29, 2023

System information


We can get System information using system info utility 


```sh 

# if want to see OS Name OS version and BIOS Version

❯ systeminfo | Select-String "OS Name","OS Version"

	/*Result*/
		OS Name:                   Microsoft Windows 10 Pro
		OS Version:                10.0.19045 N/A Build 19045
		BIOS Version:              HP Q78 Ver. 01.17.00, 8/4/2021
```


```sh 

# if want to see OS Name OS version

❯ systeminfo | Select-String "OS Name","^OS Version"

	/*Result*/
		OS Name:                   Microsoft Windows 10 Pro
		OS Version:                10.0.19045 N/A Build 19045
```


```sh 
# if want to see OS Name OS ,version and Hyper-V

❯ systeminfo | Select-String "OS Name","^OS Version" ,"Hyper-V Requirements:"

OS Name:                   Microsoft Windows 10 Pro
OS Version:                10.0.19045 N/A Build 19045
Hyper-V Requirements:      A hypervisor has been detected. Features required for Hyper-V will not be displayed.
``` 

WSL CLI commands


### 1. Version  (wsl --version (or) wsl -v )

```sh 
# wsl --version (or) wsl -v will provide version of wsl , version of distributions or version of windows 

 PS> wsl --version

	/*Result */
        WSL version: 1.2.5.0
        Kernel version: 5.15.90.1
        WSLg version: 1.0.51
        MSRDC version: 1.2.3770
        Direct3D version: 1.608.2-61064218
        DXCore version: 10.0.25131.1002-220531-1700.rs-onecore-base2-hyp
        Windows version: 10.0.19045.3208
```
### 2. List  (wsl --list (or) wsl -l [Options]

 Lists distributions.

  Options:
       --all
          List all distributions, including distributions that are
          currently being installed or uninstalled.

      --running
          List only distributions that are currently running.

      --quiet, -q
           Only show distribution names.

      --verbose, -v
          Show detailed information about all distributions.

      --online, -o
           Displays a list of available distributions for install with 'wsl.exe --install'.

```sh
❯ wsl  --list

  /*Result */
		Windows Subsystem for Linux Distributions:
		Ubuntu (Default)
		SLES-12

❯ wsl -l
  /*Result */
		Windows Subsystem for Linux Distributions:
		Ubuntu (Default)
		SLES-12

❯ wsl -l  --running
  /*Result */
	There are no running distributions.
    
❯ wsl -l  -q

 /*Result */
    Ubuntu
    SLES-12
    
❯ wsl -l  -v
  /*Result */
    NAME       STATE           VERSION
  * Ubuntu     Running         1
    SLES-12    Stopped         1
      
❯ wsl -l --online

  /*Result */
    The following is a list of valid distributions that can be installed.
    Install using 'wsl.exe --install '.

      NAME                                   FRIENDLY NAME
      Ubuntu                                 Ubuntu
      Debian                                 Debian GNU/Linux
      kali-linux                             Kali Linux Rolling
      Ubuntu-18.04                           Ubuntu 18.04 LTS
      Ubuntu-20.04                           Ubuntu 20.04 LTS
      Ubuntu-22.04                           Ubuntu 22.04 LTS
      OracleLinux_7_9                        Oracle Linux 7.9
      OracleLinux_8_7                        Oracle Linux 8.7
      OracleLinux_9_1                        Oracle Linux 9.1
      openSUSE-Leap-15.5                     openSUSE Leap 15.5
      SUSE-Linux-Enterprise-Server-15-SP4    SUSE Linux Enterprise Server 15 SP4
      SUSE-Linux-Enterprise-15-SP5           SUSE Linux Enterprise 15 SP5
      openSUSE-Tumbleweed                    openSUSE Tumbleweed      

```

### 3.  Run the specified distribution. (wsl -d  \ wsl --distribution)

```sh 
# list all distributions with status 
>  wsl -l -v
  
 /*Result */
  NAME       STATE           VERSION
* Ubuntu     Stopped         1
  SLES-12    Stopped         1
  
> wsl -d SLES-12
 /*Result */
/mnt/c/Users/user>

❯ wsl -l -v

 /*Result */
  NAME       STATE           VERSION
* Ubuntu     Stopped         1
  SLES-12    Running         1
  
> /mnt/c/Users/user> exit
 
 /*Result */
	logout

``` 


### 4.  terminate the specified distribution. (wsl -d  \ wsl --distribution)
```sh 
#wsl --terminate, -t 

❯ wsl -t SLES-12

 /*Result */

The operation completed successfully.
```

### 5. Update \ upgrate wsl package

```sh
# update wsl package using internet instead of microsoft store

> wsl --update   --web-download

/*Result */
	Checking for updates.
	The most recent version of Windows Subsystem for Linux is already installed.
```

### 6. Set WSL version 2 
```sh
> wsl --set-default-version 2

 /*Result */
    For information on key differences with WSL 2 please visit https://aka.ms/wsl2
    The operation completed successfully.
```

### 7.   Changes the version of the specified distribution.

```sh
 > wsl --set-version  SLES-12 2

 /*Result */
    For information on key differences with WSL 2 please visit https://aka.ms/wsl2
    Conversion in progress, this may take a few minutes.
    The operation completed successfully.
    
> wsl -l -v

/*Result */
      NAME       STATE           VERSION
    * Ubuntu     Stopped         1
      SLES-12    Stopped         2
      
      
> wsl --set-version  ubuntu 2

/*Result */
	For information on key differences with WSL 2 please visit https://aka.ms/wsl2
	Conversion in progress, this may take a few minutes....
    The operation completed successfully.
    
> wsl -l -v

/*Result */
      NAME       STATE           VERSION
    * Ubuntu     Stopped         2
      SLES-12    Stopped         2
```

### 8.  unregister the specified distribution

```sh
#Unregisters the distribution and deletes the root filesystem.
 
 #wsl --unregister 

> wsl --unregister SLES-12 

```
### 9.  WSL SEr

```sh
	> wsl --status

	/*Result */
	Default Distribution: Ubuntu
	Default Version: 2
```	

RunAS


When open application in windows. Application will run under logged-in user context 

if want to run application under other than logged in user context from command prompt 

```sh
runas /user:"Domain\Users" "powershell"

```

To start the process, command, or app under other than logged in user context  from powershell

```sh

$cred = (Get-Credential)
Start-Process -FilePath "Ssms.exe" -Credential $cred

Start-Process -FilePath "powershell" -Credential $Cred

```


if you can get user credentials interactively through Windows Security prompt

```sh

# Run as Administrator

Start-Process -FilePath "powershell" -Verb RunAs

# Run as from another user

Start-Process -FilePath "ssms " -Verb RunAsUser

```

Thursday, July 27, 2023

Merge Hashtables in Powershell


We can merge hashtables and perform some operations on merged hashtable  

```sh

#Function is used to merge hashtables.

function Merge-Hashtables([ScriptBlock]$Operator) {
  $Output = @{}
    ForEach ($hashtable in $input) {
        If ($Hashtable -is [Hashtable]) {
            ForEach ($key in $hashtable.Keys) {$Output.$key = If ($Output.ContainsKey($key)) {@($Output.$key) + $hashtable.$key} Else  {$hashtable.$key}}
        }
    }
    If ($Operator) {ForEach ($Key in @($Output.Keys)) {$_ = @($Output.$Key); $Output.$Key = Invoke-Command $Operator}}
    $Output
}



# Usage 


$hash1 = @{ Number = 1; Shape = "Rectangle"; Color = "Blue"}
$hash2 = @{ Number = 2; Shape = "Square"; Color ="Red"}
$hash3 = @{ Number = 3; Shape = "Circle"; Color ="Green"}

```

### Example-1

``` sh
$hash1,$hash2,$hash3 |  Merge-Hashtables

#Result 
  Name                           Value                                                                                                                   
  Color                          {Blue, Red, Green}
  Shape                          {Rectangle, Square, Circle}
  Number                         {1, 2, 3}
   
```
### Example-2

``` sh
$hash1,$hash2,$hash3 |Merge-Hashtables  {$_ -join ","}

#Result 

 Name                           Value 
 ----                           -----
 Color                          Blue,Red,Green
 Shape                          Rectangle,Square,Circle
 Number                         1,2,3                                                                                                                     
```

### Example-3

```sh
$hash1,$hash2,$hash3 |  Merge-Hashtables {$_ | Sort-Object}

#Result 
 
 Name                           Value                                                                                                                     
 ----                           -----                                                                                                                     
 Color                          {Blue, Green, Red}                                                                                                       
 Shape                          {Circle, Rectangle, Square}                                                                                               
 Number                         {1, 2, 3}       

```
### Example-4

```sh

$hash1,$hash2,$hash3 |  Merge-Hashtables {$_ | Select -First 1}

#Result 
 
  Name                           Value 
  ----                           -----
  Color                          Blue
  Shape                          Rectangle
  Number                         1        
  
```

### Example-5

```sh
$hash1,$hash2,$hash3 |  Merge-Hashtables { $_ | Select -First 2}

#Result 

 Name                           Value                                                                                                                   
 ----                           ----- 
 Color                          {Blue, Red}
 Shape                          {Rectangle, Square}
 Number                         {1, 2}     
 
```

Get assembly details using PowerShell


#### We can get details of assembly\dll using powershell

```sh
$AppBin="c:\<appPath>\<bin>"
Get-ChildItem -Path $AppBin -Filter *.dll -Recurse |
				&{Process {
                    try {
                       $AssemblyInfo=[Reflection.AssemblyName]::GetAssemblyName($_.FullName)
                        $_ | Add-Member NoteProperty FileVersion ($_.VersionInfo.FileVersion)
                        $_ | Add-Member NoteProperty AssemblyVersion ($AssemblyInfo.Version)
                        $_ | Add-Member NoteProperty Flags ($AssemblyInfo.Flags)
                        $_ | Add-Member NoteProperty CultureName ($AssemblyInfo.CultureName)
                        $_ | Add-Member NoteProperty FullyQualifiedName ($AssemblyInfo.FullName)
                        $_ | Add-Member NoteProperty PublicKeyToken ($AssemblyInfo.GetPublicKeyToken())
                    } catch {},
                    $_
                }} |
                Select Name,FileVersion,AssemblyVersion ,Flags,CultureName,FullyQualifiedName,PublicKeyToken

# otherway around 

$AppBin="c:\<appPath>\<bin>"
Get-ChildItem -Path $AppBin -Filter *.dll -Recurse | Select-Object Name
                                                                   ,@{n='FileVersion';e={$_.VersionInfo.FileVersion}}
                                                                   ,@{n='AssemblyVersion';e={[Reflection.AssemblyName]::GetAssemblyName($_.FullName).Version}}
                                                                   ,@{n='Flags';e={[Reflection.AssemblyName]::GetAssemblyName($_.FullName).Flags}}
                                                                   ,@{n='CultureName';e={[Reflection.AssemblyName]::GetAssemblyName($_.FullName).CultureName}}
                                                                   ,@{n='FullyQualifiedName';e={[Reflection.AssemblyName]::GetAssemblyName($_.FullName).FullName}}
                                                                   ,@{n='PublicKeyToken';e={[Reflection.AssemblyName]::GetAssemblyName($_.FullName).GetPublicKeyToken()}}

```

#### Get details of assemblies loaded in the current powershell session

```sh
[System.AppDomain]::CurrentDomain.GetAssemblies() | 
							Where-Object Location |
 							Sort-Object -Property FullName | 
                            Select-Object -Property FullName
                                                  , Location
                                                  , GlobalAssemblyCache
                                                  , IsFullyTrusted |
                            Out-GridView

```

Wednesday, July 26, 2023

WSL file system and access Host OS file system from WSL


Access Host OS file system from WSL distribution 

```sh 
 	/mnt/c/users/<HostOS-UserId>
```
WSL home path 
```sh 
 	/home /<WSL-UserId>
```

Access WSL installed distribution location from Host OS (Windows)

```sh 
 	\\wsl$\
     \\wsl$\<distribution-name>
```

Configuring a proxy for WSL



Guest OS (WSL) is not able to connect to undleying internet of Host OS (Windows) when we connect to VPN  in the Host OS (Windows)

Before configuring Proxy in guest OS (WSL). First we need to perform communication check whether Guest OS (WSL) and Host OS are communicating each other not 


 - Communication check between Guest OS and Host OS<\u>
 
   1.  To know IPV4 Address of Ethernet Adapter for WSL, type ipconfig  (or) ipconfig /all in command shell of Host OS.
   2.  To know Ip address of proxy , type ping  in command shell of Host OS
   3.  to know ip address of WSL , type , hostname -I  (or) ifconfig in guest OS (WSL)
   
  Then 
  
  1. Ping ip address of WSL from Host OS  ( ex: Ping  <ip-Address-of-WSL>).   if packets are transferred and received successfully then it means  HostOS is able to communicate with Guest OS (WSL)
  
  2. ping IPV4 Address of Ethernet Adapter for WSL  and ping Ip address of proxy from Guest OS (WSL) . if packets are transferred and received successfully then it means  Guest-OS (WSL) is able to communicate with Host-OS.


if both are communicating each other then follow below steps to configure proxy in WSL.


### Proxy DNS name resolution in Guest OS

```sh
# To resolve proxy dns name in Guest OS , add proxy ip address and dns names of proxy  in /etc/hosts

sudo nano /etc/hosts

#Add below text with proper ip address and dns names of Proxy

#xxx.xx.xx.xx   proxy.example.com   proxy-dev.example.com   
```


### Add proxy configuration in  /etc/apt/apt.conf.d/proxy.conf file for execute apt-get , apt install command  with internet

```sh
#Open /etc/apt/apt.conf.d/proxy.conf in nano editor.  note: use vi editor  

sudo nano /etc/apt/apt.conf.d/proxy.conf
   
   
  Acquire::http::proxy  http://proxy.example.com:7007;
  Acquire::ftp::proxy  http://proxy.example.com:7007;
  Acquire::https::proxy http://proxy.example.com:7007;
  
  #Note: Please use correct proxy URL and port number



#if proxy configuration is enable in proxy.conf  . no need to add proxy config in apt.conf else you can add . this configuration will be used by apt command
 
   sudo nano /etc/apt/apt.conf

   Acquire::http::proxy  http://proxy.example.com:7007;
   Acquire::ftp::proxy  http://proxy.example.com:7007;
   Acquire::https::proxy http://proxy.example.com:7007;
   
  #Note: Please use correct proxy URL and port number

# then you can upgrade packages and install new packages using apt cli

#example

	#sudo apt-get update -y
	#sudo apt install ipmiutil
	#sudo apt install dotnet-host
    #sudo apt install net-tools
```

To avoid updating proxy configuration in conf file by restarting WSL. You can add proxy configuration in profile 

```sh 
sudo nano  ~/.profile

	export https_proxy=http://proxy.example.com:7007
    export http_proxy=http://proxy.example.com:7007

#Note: Please use correct proxy URL and port number

#To avoid restarting the WSL you can run the command:

source ~/.profile

```

### Below is the proxy configuration for wget command 


```sh 
 sudo nano ~/.wgetrc
    
    http_proxy=http://proxy.example.com:7007
    https_proxy=http://proxy.example.com:7007
    use_proxy=on

#Note: Please use correct proxy URL and port number

```

### Below is the proxy configuration for git

```sh
 git config —-global http.proxy http://proxy.example.com:7007
```

### Below is the proxy configuration for git

```sh
	npm set proxy http://proxy.example.com:7007
	npm set https-proxy http://proxy.example.com:7007
```



Tuesday, July 25, 2023

Upload and Download files.


 The Start-BitsTransfer cmdlet creates a Background Intelligent Transfer service  (BITS) transfer job to transfer one or more  files between a client computer and server.
 

### 1.following command will create BITS transfer job that downloads a file from server
 

```sh 
    Start-BitsTransfer -Source "http://server/test/file1.txt"  -Destination "C:\clientdocs\testfile1.txt"
   			#or
 	Start-BitsTransfer "http://server/test/file1.txt"  "C:\clientdocs\testfile1.txt"
```		
 
### 2.following command will create BITS transfer job that upload a file to server
 
```sh
 	Start-BitsTransfer  -Source "C:\docs\testfile1.txt"  -Destination "http://server/test/file1.txt"  -TransferType Upload 
    	   #or
 	Start-BitsTransfer "C:\docs\testfile1.txt" "http://server/test/file1.txt"  -TransferType Upload
```

### 3.following command will create BITS transfer jobs that download multiple files 

```sh
     Import-CSV filesToDownload.txt | Start-BitsTransfer -Asynchronous -Priority Normal 
     
     #Note: The content of the filesToDownload.txt resemble the following  information
       <#
           Source , Destination 
           "http://server/test/file1.txt","C:\clientdocs\testfile1.txt"
           "http://server/test/file2.txt","C:\clientdocs\testfile2.txt"
           "http://server/test/file2.txt","C:\clientdocs\testfile2.txt"
       #>#
```
 
### 4.following command will create BITS transfer jobs that download multiple files.

```sh
    Start-BitsTransfer  -Source  "C:\docs\*.log"  -Destination "\\server1\docs\"  -TransferType Download
```
 
### 5.following command will create BITS transfer jobs that download multiple files 
 
```sh
    Import-CSV filestoUpload.txt |Start-BitsTransfer  -TransferType Upload
    
      #Note: The content of the files.txt resemble the following  information
       <#
           Source , Destination 
           "C:\clientLogs\testfile1.log" , "http://server/logs/file1.log"
           "C:\clientLogs\testfile2.log" , "http://server/logs/file2.log"
           "C:\clientLogs\testfile2.log" , "http://server/logs/file2.log"
       #>
```
 
  

Monday, July 24, 2023

Chocolatey Package Manager


Chocolatey is a package manager for Windows that allows you to install software packages from the command line. It is similar to apt-get on Linux


### Installation of Chocolatey package CLI 

```sh 
Set-ExecutionPolicy Bypass -Scope Process -Force; 

[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; 

iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))

```

### Install software package using Chocolatey CLI.

We can install software packages in Windows using choco CLI 

 Syntax 
```sh 
choco install 
```

 Examples 
```sh 
choco install keeweb 		                    <# install keeweb package using choco CLI #>

choco install visualstudio2019-workload-python 	<# install VS 2019 template to python development#>
```

### List out installed chocolatey packages in the windows system.

 Syntax 
```sh 
choco list  
```

### Uninstall software package using Chocolatey CLI.

We can install software packages in Windows using choco CLI 

 Syntax 
```sh 
choco uninstall 
```

 Examples 
```sh 
choco uninstall keeweb 		                       <# uninstall keeweb package using choco CLI #>

choco uninstall visualstudio2019-workload-python 	<# uninstall VS 2019 template to python development#>
```

### Upgrade software package using Chocolatey CLI.

We can upgrade software packages in Windows using choco CLI 

 Syntax 
```sh 
choco upgrade 
```

 Examples 
```sh 
choco upgrade keeweb 		                       <# upgrade keeweb package using choco CLI #>

choco upgrade visualstudio2019-workload-python 	   <# upgrade VS 2019 template to python development#>

choco upgrade chocolatey                           <# upgrade chocolatey package #> 

choco upgrade notepadplusplus googlechrome atom 7zip    <# upgrade notepadplusplus,googlechrome ,atom,7zip packages #> 

choco upgrade all --except="skype,conemu"               <# will upgrade all packages except for Skype and ConEmu #> 
```


How to log message using Select query in SQL and Print statement


Sometimes , Its not easy to write log\print messages for DML operations on set of rows in table.
We can use store text in xml using select query and print messages for logging when performing DML operations on set of rows in table ```sql Declare @NewLine As char(2) = char(13)+ char(10) ,@empty as char(1)='' ,@xmltext as xml, ,@CurrentTimp as DateTime =Current_timestamp ,@CurrentUser as Varchar(20) =Current_User ,@ActivityID =12; Declare @folios as table ( ID INT Identity(1,1),PortfolioId int, Name Varchar (10) , UserName varchar(15) , SSN Char(9)) Insert @folios Select PortfolioId,Name, UserName,SSN,IsActive from Portfolio (nolock) Pf where pf.IsActive=0 and pf.SSN not like '000%' BEGIN Try BEGIN Transaction Update Portfolio Set IsActive =1 from @folios fol join Portfolio (nolock) Pf on pf.PortfolioId=fol.PortfolioId if (@@rowcount >0 ) Begin Insert into AuditLog(ActivityID ,Message ,AcivityTimeStamp ,User) Select @ActivityID ,'Portfolio -'+pf.Name+ 'has been active for user '+ pf.UserName +' with SSN '+ STUFF(pf.SSN,1,5,'XXX-XX-') , @CurrentTimp , @CurrentUser From @folios Select @xmltext =(Select 'Portfolio -'+pf.Name+ 'has been active for user '+ pf.UserName +' with SSN '+ STUFF(pf.SSN,1,5,'XXX-XX-') From @folios [temp] for XML Auto) PRINT Replace(Replace(Convert(NVARCHAR(MAX) ,@xmltext),'<temp txt="',@empty),'/<',@NewLine) END Commit Transaction END TRY Begin Catch Select Error_Number() as ErrorNumber , Error_Message() as ErrorMessage; if (XACT_State())=-1 Begin Print N 'The Transaction is in an uncommittable state. Rolling back transaction.' Rollback Transaction; End if (XACT_STATE())=1 Begin PRINT N'The Transaction is committable. Committing transaction.' COMMIT Transaction End End Catch ```

Sunday, July 23, 2023

How to use crypto currency value using CryptoFinance extension


Go to Extensions  > Add-ons  > Get Add-Ons

Search for CryptoFinance in Marketplace and install 

```
Syntax
	=CRYPTOFINANCE(Curryticker)

Usuage \Examples :
	=CRYPTOFINANCE("DOGEUSD")
	=CRYPTOFINANCE("ETHUSD")
	=CRYPTOFINANCE("BTCUSD")
```

Wednesday, July 19, 2023

Azure Functions Core Tools -Installation


1. install using [MSI](https://go.microsoft.com/fwlink/?linkid=2174087)
2. install using  npm 
    
```sh
 	npm i -g azure-functions-core-tools@4 --unsafe-perm true
```
3. install using chocolatey 
   	
```sh
 	choco install azure-functions-core-tools
```
4. install using winget 

```sh
   winget install Microsoft.AzureFunctionsCoreTools
```
5.  Set up package feed in Linux machine 
    	
``` sh
 # Setup package feed
 	wget -q https://packages.microsoft.com/config/ubuntu/19.04/packages-microsoft-prod.deb
    sudo dpkg -i packages-microsoft-prod.deb
 # install 
    sudo apt-get update
     sudo apt-get install azure-functions-core-tools-4
```
    
 

Compress and Expand archive files.


 - We can compress files into archive file using  ps script.

```sh

# Example
	$compress = @{
  				Path = "C:\Reference\Readme-draft.md", "C:\Users\Downloads\*.pdf"
  				CompressionLevel = "Fastest"
  				DestinationPath = "C:\Archives\Draft-docs.zip"
				}
	
    Compress-Archive @compress

```
 
 - We can expand archive file using  ps script.

```sh
      
#Example-1      
      Expand-Archive -LiteralPath 'C:\Downloads\Azure.Functions.Cli.min.win-x64.4.0.4865.zip'  `
      				 -DestinationPath C:\Users\rkolla\Downloads\Azure.Functions.Cli.min.win-x64.4.0.4865
      
#Example-2            
      Expand-Archive -LiteralPath 'C:\Downloads\node-v18.17.0-win-x64.zip' `
                     -DestinationPath C:\Users\rkolla\Downloads\node-v18.17.0-win-x64
```

Tuesday, July 18, 2023

Tips for Excel

  
1. We can set auto row width and auto column width in the excel 

  ```sh
	# Ctrl+A      - Select all columns (or) select particular area (set of column & rows) 
	# Alt+H+O+A  - Set Auto Row Height
    # Alt+H+O+I  - Set Auto Column Width

	```
2. We can apply filters for table data in Excel spreadsheet
	
    ```sh
		# Ctrl+A     - Select all columns (or) select particular area (set of column & rows) 
		# Alt+H+S+F  -  Apply Filters
    
	```

3. We can apply boards to shell in Excel spreadsheet


	```sh
  		# Ctrl+A     - Select all columns (or) select particular area (set of column & rows) 
        # Alt+H+B+A  -  Apply all boarders
	```
<\pre>

How to insert convert Comma\tab separated text into table

  
We can insert \convert comma(or) tab separted text into table 

  
```sh
	# Ctrl+A      - Select text to insert into table .
	# Alt+N+T+I   - Convert into table.

```

<\pre>

View IIS logs in grid view mode


 We can view today's iis logs in grid view mode using below ps script.


```sh
$IISLogs ="C:\\InetPub\\Logs\\LogFiles\\W3SVC1\\"
$Today=$(Get-Date -F 'yyMMdd')
Function Out-GridViewIISLog ($File) {
    $Headers = @((Get-Content -Path $File -ReadCount 4 -TotalCount 4)[3].split(' ') | Where-Object { $_ -ne '#Fields:' });
    Import-Csv -Delimiter ' ' -Header $Headers -Path $File | Where-Object { $_.date -notlike '#*' } | Out-GridView -Title "IIS log: $File";
};


Out-GridViewIISLog -File $(Join-path  $IISLogs "u_ex.$Today.log")

```