Search This Blog

Google Analytics

Showing posts with label Code Snippets. Show all posts
Showing posts with label Code Snippets. Show all posts

Friday, November 07, 2025

Recursively List All Files with PowerShell

If you are working with PowerShell and need a fast way to list all files in a directory, including those buried in subfolders, this one-liner will work:
Get-ChildItem -Path . -Recurse -File | Select-Object FullName
This script performs a recursive search starting from the current directory (.), finds all files (excluding folders), and outputs their full paths.

Tuesday, October 14, 2025

PowerShell Tip: Bulk Appending File Extensions with One-Liner Magic

Ever found yourself staring at a folder full of files and wishing you could batch append them all with a .txt suffix? PowerShell makes this delightfully simple with a one-liner:
Get-ChildItem -File | Rename-Item -NewName {$_.Name + '.txt'}
To expand further to include files in all sub folders, use below instead.
Get-ChildItem -File -Recurse | Rename-Item -NewName { $_.Name + '.txt' }
If you wish to rollback what you just did, use the following:
Get-ChildItem -Path . -Recurse -File -Filter "*.txt" | ForEach-Object {
    $newName = [System.IO.Path]::GetFileNameWithoutExtension($_.Name)
    Rename-Item -Path $_.FullName -NewName $newName
}
Feel free to replace the txt with a different one based on your needs!

Wednesday, January 08, 2025

Copy directories recursively from source to destination

Robocopy, short for "Robust File Copy" is an advanced command-line utility included in Windows. It's designed to copy files and directories with more features and control than the basic copy commands. If you need to efficiently and reliably replicate a large number of files and folders, Robocopy is your go-to tool.
robocopy source dest /s /e

Wednesday, April 10, 2024

Useful openssl commands to generate certificates and keys

I hope the following will come handy when it comes to generating key pairs and certificates.
# Generate a Private Key
openssl genrsa -out privatekey.pem 2048

# Generate a self-signed certificate
openssl req -new -x509 -key privatekey.pem -out self_signed_certificate.pem -days 365

# Convert PEM certificate to CER format
openssl x509 -inform PEM -in self_signed_certificate.pem -outform DER -out self_signed_certificate.cer

# Convert a PEM certificate to a PFX (PKCS#12) file
openssl pkcs12 -export -out certificate.pfx -inkey privatekey.pem -in self_signed_certificate.pem

# Extract a private key from a PFX file (contain bag attributes)
# openssl pkcs12 -in certificate.pfx -nocerts -nodes -out privatekey_frompfx.pem
openssl pkcs12 -in certificate.pfx -nocerts -nodes -out privatekey_frompfx.key

# Extract a private key (no bag attributes) - identical to privatekey.pem
openssl rsa -in privatekey_frompfx.key -out privatekey_frompfx.key

# Extract public key from key pair
openssl rsa -in privatekey_frompfx.key -pubout -out publickey.key
#openssl rsa -in privatekey.pem -pubout -out publickey2.key

# Convert CER to CRT
openssl x509 -inform DER -in self_signed_certificate.cer -out self_signed_certificate.crt
#openssl x509 -inform PEM -in self_signed_certificate.cer -out self_signed_certificate.crt

# Convert CRT to CER
openssl x509 -in self_signed_certificate.crt -outform DER -out self_signed_certificate2.cer

#####
# Generate a Certificate Signing Request (CSR) - optional if going to generate a self-signed
#openssl req -new -key privatekey.pem -out certificate_request.csr
#openssl x509 -req -in certificate_request.csr -signkey privatekey.pem -out self_signed_certificate3.crt

Sunday, January 14, 2024

Oracle: Find out total number of records of all tables

An efficient method to find out the total record counts of all tables in an Oracle database.
select table_name,
  to_number(extractvalue(xmltype(dbms_xmlgen.getxml('select count(*) c from '||owner||'.'||table_name)),'/ROWSET/ROW/C')) as count
from all_tables
where owner = 'SchemaName';

Hope it helps.

MSSQL: Find out total number of records of all tables

An efficient method to find out the total record counts of all tables in a MSSQL database.
SELECT tbl.name, CAST(p.rows AS int) 'count', tbl.schema_id, SCHEMA_NAME(tbl.schema_id) schema_name
FROM
  sys.tables AS tbl
  INNER JOIN sys.indexes AS idx ON idx.object_id = tbl.object_id AND idx.index_id < 2
  INNER JOIN sys.partitions AS p ON p.object_id = CAST(tbl.object_id AS int) AND p.index_id = idx.index_id
--WHERE ((SCHEMA_NAME(tbl.schema_id) = 'dbo'))
ORDER BY 2 DESC

Hope it helps.

Monday, July 17, 2017

Restore Database Backup Over a Network Drive

How do you restore a Microsoft SQL database backup over a network drive without having to download to local? Since the database server is run as a service under an account that often without network access permission, it wouldn't be possible to be able to select the network drive/path when you are performing a restore. Nonetheless, we are not left without workaround.

To restore database backup over a network, you will need to run the following SQL statements using your SQL Management Studio.

--enable to show advanced options
EXEC sp_configure 'show advanced options', 1
GO
--apply changes for show advanced options
RECONFIGURE
GO
--enable xp_cmdshell
EXEC sp_configure 'xp_cmdshell', 1
GO
--apply changes for xp_cmdshell
RECONFIGURE
GO
--replace network path, username and password accordingly
EXEC xp_cmdshell 'NET USE Z: \\SERVER\Path password /USER:Domain\Username'
GO

Once the above are executed, you should be able to choose Z:\ network drive to restore your database backup file. I hope it helps.

Saturday, April 23, 2016

How to find out which w3wp.exe PID corresponds to which application pool?

Should we have more than one website hosted on IIS, it may be difficult to identify which web application is the one listed on the task manager especially when the application pools are all on Network Service.

Task Manager showing multiple w3wp.exe processes

Each w3wp.exe process has a PID (process identifier), but to tell which PID belongs to which application pool, it is not straightforward.

One method to find out the application pool is to run the appcmd command on command prompt from C:\Windows\system32\inetsrv directory.

appcmd list wp

appcmd command to show application pool of a PID

Simply match the PID against the application pool name. I hope it helps.

Tuesday, March 01, 2016

How do I enable ASP.NET 4.5 on Windows 10?

Despite you may have installed Microsoft .NET Framework 4.5 on your Windows, IIS has to be installed and ASP.NET to be enabled separately.

To install IIS, you will need to turn on Internet Information Services feature.

The next step to get ASP.NET running is to enable ASP.NET. Prior to Windows 8, we used to run aspnet_regiis /i command. Unfortunately, this command no longer works. I have tried the following command instead to get ASP.NET enabled.

dism /online /enable-feature /all /featurename:IIS-ASPNET45

Tuesday, November 24, 2015

MsSQL: Shrink ALL Databases Using 1 Single Line of SQL Statement

Over time, the database logs on your database server may take up significant amount of disk space especially if there are many databases with lots of transactions. One quick method to free up disk space is to "shrink" your databases. Instead of shrinking one database at a time using the GUI, you can run a single line of SQL statement to do just that.

EXEC sp_MSForEachDB 'DBCC SHRINKDATABASE (''?'' , 0)'

Hope it helps.

Monday, November 09, 2015

Find the Wi-Fi network password in your saved list on Windows

There may be occasion you may have a second mobile device and would like to be connected to the Wi-Fi network but sadly, you could have forgotten the password completely. What you need to do now is to run a command on the Windows command prompt in administrative mode to reveal the already added Wi-Fi network password in clear.

Replace THE_SSID with your own Wi-Fi SSID.

The below will show details of the Wi-Fi network.

netsh wlan show profile name=THE_SSID key=clear

To see only the password ignoring the rest of the details, feed it with the findstr command like below.

netsh wlan show profile name=THE_SSID key=clear | findstr Key

For similar hack for Mac and Linux, read How to Find the Wi-Fi Password of your Current Network.

Tuesday, June 30, 2015

Rebuild all Indexes on a Microsoft SQL Server

As part of database maintenance, a DBA may wish to do periodical rebuild of all indexes. The below may come handy.
EXEC sp_MSForEachTable 'ALTER INDEX ALL ON ? REBUILD'

Wednesday, April 15, 2015

MsSQL Split Function

The following demonstrates how to do a string Split using a character delimiter.

Edited: [dbo].[Split_PerformanceEnhanced] added - better performance results (31 July 2017).

--SQL function to do split (performance enhanced)
CREATE FUNCTION [dbo].[Split_PerformanceEnhanced]
(
 @List NVARCHAR(MAX),
 @Delimiter VARCHAR(5)
)  
RETURNS @RtnValue TABLE
(
 ID INT IDENTITY(1,1),
 Data VARCHAR(MAX)
) 
AS
BEGIN
 INSERT INTO @RtnValue(Data)
  SELECT [Value] FROM 
    ( 
    SELECT 
     [Value] = LTRIM(RTRIM(SUBSTRING(@List, [Number],
     CHARINDEX(@Delimiter, @List + @Delimiter COLLATE Latin1_General_100_BIN2, [Number]) - [Number])))
    FROM (SELECT Number = ROW_NUMBER() OVER (ORDER BY name)
     FROM sys.all_objects) AS x
     WHERE Number <= LEN(@List)
     AND SUBSTRING(@Delimiter + @List, [Number], LEN(@Delimiter)) = @Delimiter
    ) AS y

 RETURN;
END
GO
--Test out the SQL function
SELECT * FROM dbo.Split_PerformanceEnhanced('one|two|three|four', '|')
GO
Below SQL function still works but prefer the above new performance enhanced version.
--SQL function to do split
CREATE FUNCTION [dbo].[Split]
(
 @RowData NVARCHAR(MAX),
 @SplitOn CHAR(1)
)  
RETURNS @RtnValue TABLE
(
 ID INT IDENTITY(1,1),
 Data VARCHAR(MAX)
) 
AS
BEGIN
 DECLARE @count INT
 SET @count = 1

 WHILE (CHARINDEX(@SplitOn COLLATE Latin1_General_100_BIN2, @RowData) > 0)
 BEGIN
  INSERT INTO @RtnValue (data)
  SELECT Data = LTRIM(RTRIM(SUBSTRING(@RowData, 1, CHARINDEX(@SplitOn COLLATE Latin1_General_100_BIN2, @RowData) - 1)))
  SET @RowData = SUBSTRING(@RowData, CHARINDEX(@SplitOn COLLATE Latin1_General_100_BIN2, @RowData) + 1, LEN(@RowData))
  SET @count = @count + 1
 END

 INSERT INTO @RtnValue (data)
 SELECT Data = LTRIM(RTRIM(@RowData))

 RETURN
END
GO
--Test out the SQL function
SELECT * FROM dbo.Split('one|two|three|four', '|')
GO

Tuesday, March 25, 2014

Image Resize in C#

The below code snippet (adapted from Stackoverflow) will do a image resize to a desired width in pixels. I hope it helps.

/// <summary>
/// Resize image to desired dimension based on width
/// </summary>
/// <param name="strSrcPath">Full absolute path of image source</param>
/// <param name="strDestPath">Full absolute path for resized image to be saved to</param>
/// <param name="iNewWidth">New desired width in pixels</param>
/// <param name="blnIgnoreIfNewWidthLarger">Do not resize image should new desired width is larger than width of original image if set to true</param>
public void Resize(string strSrcPath, string strDestPath, int iNewWidth, bool blnIgnoreIfNewWidthLarger)
{
 bool blnDoNotResize = false;
 System.Drawing.Image objSrcImage;
 System.Drawing.Bitmap objDestImage;
 System.Drawing.Graphics objGrapics;

 try
 {
  objSrcImage = System.Drawing.Image.FromFile(strSrcPath);

  int iSrcWidth = objSrcImage.Width;
  int iSrcHeight = objSrcImage.Height;

  blnDoNotResize = ((iSrcWidth == iNewWidth) || (blnIgnoreIfNewWidthLarger && iNewWidth > iSrcWidth));

  if (!blnDoNotResize)
  {
   int iNewHeight = iSrcHeight * iNewWidth / iSrcWidth;

   int iSrcX = 0, iSrcY = 0, iDestX = 0, iDestY = 0;
   float fPercent = 0, fPercentW = 0, fPercentH = 0;

   fPercentW = ((float)iNewWidth / (float)iSrcWidth);
   fPercentH = ((float)iNewHeight / (float)iSrcHeight);
   if (fPercentH < fPercentW)
   {
    fPercent = fPercentH;
    iDestX = System.Convert.ToInt16((iNewWidth - (iSrcWidth * fPercent)) / 2);
   }
   else
   {
    fPercent = fPercentW;
    iDestY = System.Convert.ToInt16((iNewHeight - (iSrcHeight * fPercent)) / 2);
   }

   int iDestWidth = (int)(iSrcWidth * fPercent);
   int iDestHeight = (int)(iSrcHeight * fPercent);

   objDestImage = new System.Drawing.Bitmap(iNewWidth, iNewHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
   objDestImage.SetResolution(objSrcImage.HorizontalResolution, objSrcImage.VerticalResolution);

   objGrapics = System.Drawing.Graphics.FromImage(objDestImage);
   objGrapics.Clear(System.Drawing.Color.Black);
   objGrapics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

   objGrapics.DrawImage(objSrcImage,
    new System.Drawing.Rectangle(iDestX, iDestY, iDestWidth, iDestHeight),
    new System.Drawing.Rectangle(iSrcX, iSrcY, iSrcWidth, iSrcHeight),
    System.Drawing.GraphicsUnit.Pixel);

   objGrapics.Dispose();

   objSrcImage.Dispose();

   objDestImage.Save(strDestPath);
   objDestImage.Dispose();
  }
  else
  {
   objSrcImage.Dispose();
   System.IO.File.Copy(strSrcPath, strDestPath, true);
  }
 }
 catch (Exception ex)
 {
  throw ex;
 }
 finally
 {
  objSrcImage = null;
  objDestImage = null;
  objGrapics = null;
 }
}

Wednesday, January 01, 2014

How to defer loading of javascript efficiently using the Google way?

If there is a piece of code that is intended to be loaded after a webpage finishes loading, one efficient method as recommended by Google is to use listeners. An article on feedthebot illustrates the Google's method. The following code should be placed in your HTML just before the </body> tag. Also, all code blocks supposed to be delayed are to be placed in an external js file (defer.js in this case).

<script type="text/javascript">
function downloadJSAtOnload() {
    var element = document.createElement("script");
    element.src = "defer.js";
    document.body.appendChild(element);
}

if (window.addEventListener)
    window.addEventListener("load", downloadJSAtOnload, false);
else if (window.attachEvent)
    window.attachEvent("onload", downloadJSAtOnload);
else
    window.onload = downloadJSAtOnload;
</script>

Tuesday, October 29, 2013

HtmlEncode and HtmlDecode In JavaScript

In web development, we often need to encode a string especially input from user so data with potential malicious intention when displayed will be safe. On server side, we can use e.g. HtmlUtility.HtmlEncode (in ASP.NET for encode) and HtmlUtility.HtmlDecode (in ASP.NET for decode).

What if we need one in JavaScript? Here's how to do just that!

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<script language="javascript" type="text/javascript">
<!--
    function htmlEncode(value) {
        return $('<div/>').text(value).html();
    }

    function htmlDecode(value) {
        return $('<div/>').html(value).text();
    }

    var s = "<b>hello's world</b>";
    var encoded = htmlEncode(s);
    var decoded = htmlDecode(encoded);

    alert(encoded);
    alert(decoded);
//-->
</script>

Thursday, August 15, 2013

JAVA: Get MD5 Hash On String

The following demonstrates how to perform MD5 hash on string. For it to run, you will need to import these 2 packages.
  • java.security.MessageDigest
  • javax.xml.bind.annotation.adapters.HexBinaryAdapter
public static void main(String[] args) {
    try {
        String hash1 = computeMD5Hash1("hello world");
        String hash2 = computeMD5Hash2("hello world");
        System.out.println(hash1);
        System.out.println(hash2);
    } catch (Exception e) {
    }
}

//using HexBinaryAdapter to convert byte array to string
public static String computeMD5Hash1(String plainText) {
    String hash = "";
    try {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        hash = (new HexBinaryAdapter()).marshal(md5.digest(plainText.getBytes()));
        hash = hash.toUpperCase();
    } catch (Exception e) {
        hash = "";
    }

    return hash;
}

//no library to convert byte array to string
public static String computeMD5Hash2(String plainText) {
    String hash = "";
    try {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        byte[] bb = md5.digest(plainText.getBytes());
        for (byte b : bb)
            hash += String.format("%02X", b & 0xff);
    } catch (Exception e) {
        hash = "";
    }

    return hash;
}

Monday, June 10, 2013

MSSQL: Get All Stored Procedures With References to a Table

AFAIK, there is no built-in feature to generate a list of stored procedures that made references to a specific database table. The following help me to do just that.

SELECT DISTINCT so.name
FROM syscomments sc INNER JOIN sysobjects so ON sc.id = so.id AND so.xtype = 'P'
WHERE sc.TEXT LIKE '%TABLE_NAME%'

Sunday, May 26, 2013

MSSQL: Generate Random String Using SQL

The following will generate a random fixed-length string using SQL. Simply pass in a string of accepted characters and the length of the random string to be generated.

IF ISNULL(object_id('cspRandomString'),0)<>0 DROP PROC cspRandomString
IF ISNULL(object_id('fnGenRandomInteger'),0)<>0 DROP FUNCTION fnGenRandomInteger
GO
CREATE function fnGenRandomInteger(@MinValue int, @MaxValue int, @Seed float)
returns int
as
begin
-- =============================================
-- Author:        Loh Hon Chun
-- =============================================
 return ((@MaxValue + 1) - @MinValue) * @Seed + @MinValue
end
go
CREATE procedure cspRandomString (
 @Result varchar(255) output,
 @AcceptedChars varchar(255),
 @Length int
)
as
begin
-- =============================================
-- Author:        Loh Hon Chun
-- =============================================
 set nocount on

 declare @ret char(255)
 declare @i int, @pos int
 
 set @Result = ''
 set @i = 0

 if LEN(@AcceptedChars) > 0
 begin
  while @i < @Length
  begin
   set @pos = dbo.fnGenRandomInteger(1, LEN(@AcceptedChars), RAND(CONVERT(VARBINARY, NEWID())))
   set @Result = @Result + CAST(SUBSTRING(@AcceptedChars, @pos, 1) AS VARCHAR(1))
   set @i = @i + 1
  end
 end
end
go

declare @result varchar(255)
declare @acceptedChars varchar(255)
declare @length int

set @acceptedChars = '0123456789'
set @length = 7
exec cspRandomString @Result=@result output, @AcceptedChars=@acceptedChars, @Length=@length
print @result
go

Saturday, April 27, 2013

ASP.NET fails to detect IE10 causing _doPostBack is undefined JavaScript error

Should you encounter _doPostBack is undefined JavaScript error on IE 10, it is because there is a bug in the browser definition files that shipped with .NET 2.0 and .NET 4.

Scott Hanselman published two ways to fix this: one is a machine-wide fix, the other is a way to fix individual sites. The replacement of the "fixed" ie.browser file will supposedly resolve the problem but it somehow didn't quite work for me. If that file didn't work for you, you may wish to use the below instead.

~\App_Browsers\ie.browser

<browsers>
    <!-- Mozilla/5.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4325) -->
    <browser id="IE6Plus" parentID="IE">
        <identification>
            <capability name="majorversion" match="^[6-9]|\d{2,}$" />
        </identification>

        <capabilities>
            <capability name="ecmascriptversion"    value="3.0" />
            <capability name="jscriptversion"       value="5.6" />
            <capability name="javascript"           value="true" />
            <capability name="javascriptversion"    value="1.5" />
            <capability name="msdomversion"         value="${majorversion}.${minorversion}" />
            <capability name="w3cdomversion"        value="1.0" />
            <capability name="ExchangeOmaSupported" value="true" />
            <capability name="activexcontrols"      value="true" />
            <capability name="backgroundsounds"     value="true" />
            <capability name="cookies"              value="true" />
            <capability name="frames"               value="true" />
            <capability name="javaapplets"          value="true" />
            <capability name="supportsCallback"     value="true" />
            <capability name="supportsFileUpload"   value="true" />
            <capability name="supportsMultilineTextBoxDisplay" value="true" />
            <capability name="supportsMaintainScrollPositionOnPostback" value="true" />
            <capability name="supportsVCard"        value="true" />
            <capability name="supportsXmlHttp"      value="true" />
            <capability name="tables"               value="true" />
            <capability name="supportsAccessKeyAttribute"    value="true" />
            <capability name="tagwriter"            value="System.Web.UI.HtmlTextWriter" />
            <capability name="vbscript"             value="true" />
        </capabilities>
    </browser>

    <!-- Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0;) -->
    <browser id="IE6to9" parentID="IE6Plus">
      <identification>
        <capability name="majorversion" match="^[6-9]$" />
      </identification>
    </browser>

    <!-- Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0;) -->
    <browser id="IE7" parentID="IE6to9">
        <identification>
            <capability name="majorversion" match="^7$" />
        </identification>
        <capabilities>
            <capability name="jscriptversion" value="5.7" />
        </capabilities>
    </browser>

    <!-- Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729) -->
    <browser id="IE8" parentID="IE6to9">
        <identification>
            <capability name="majorversion" match="^8$" />
        </identification>
        <capabilities>
            <capability name="jscriptversion" value="6.0" />
        </capabilities>
    </browser>

  <!-- Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729) -->
  <browser id="IE9" parentID="IE6to9">
    <identification>
      <capability name="majorversion" match="^9$" />
    </identification>
    <capabilities>
      <capability name="jscriptversion" value="6.0" />
    </capabilities>
  </browser>

  <!-- Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0) -->
  <browser id="IE10Plus" parentID="IE6Plus">
    <identification>
      <capability name="majorversion" match="\d{2,}" />
    </identification>
    <capabilities>
      <capability name="jscriptversion" value="6.0" />
    </capabilities>
  </browser>

  <gateway id="IEbeta" parentID="IE">
        <identification>
            <capability name="letters" match="^([bB]|ab)" />
        </identification>

        <capture>
        </capture>

        <capabilities>
            <capability name="beta"    value="true" />
        </capabilities>
    </gateway>
</browsers>

Popular Posts